Read[stream, Number] will return a single read number. We can use a number of standard, documented types instead of Number, such as String, Expression, Real, etc.

Is it possible to get Read to immediately apply a function to the expression that was just read, similarly to how ToExpression applies its third argument?


1 Answer 1


Yes! This is documented under Details:

You can use Read to get objects to insert into any expression structure, not necessarily a list. Example: Read[stream,Hold[Expression]] gets an expression and places it inside Hold.

What this means is that we can use any compound expression as the second argument of Read. Any type names (such as Number, Real, Expression, etc.) that appear in this compound expression will be replaced by the values that are read.

Suppose we have an input file containing

1 2 3+4

Then we can read and process the data at the same time this way:

Read[str, Number]  -->  1      read one number

Read[str, {Number, Number}]  -->  {1, 2}     read two numbers

Read[str, f[Number, Number]]  -->  f[1, 2]   read two numbers and wrap them in f instead of List

Read[str, {{Number, Number}, Expression}]  -->  {{1, 2}, 7}    two numbers and an expression

Read[str, {{Number, Number}, Hold[Expression]}  --> {{1, 2}, Hold[3+4]}    two numbers and a held expression

The two most prominent applications are the ones shown in the documentation:

  • Read values grouped into lists, Read[..., {Number, Number, Number}]

  • Read held expressions using Read[..., HoldComplete[Expression]]. The expression is inserted into HoldComplete before evaluation.

  • $\begingroup$ I posted this because I did not know about this feature and even after reading the documentation it took me a while to get the point. I thought others will find it useful. Thanks to @Kuba for showing Read[..., Hold[Expression]]! $\endgroup$
    – Szabolcs
    Aug 24, 2016 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.