# Can Read[] apply a custom function automatically to the read values?

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?

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, 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.

• 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]]! – Szabolcs Aug 24 '16 at 12:09