Power Tools: Anonymous Functions, List.map & the Pipe Operator
10 min · OCaml
Write inline functions, transform lists with List.map/List.filter, and chain steps with |>.
Enemy 1 of 5
Anonymous functions with fun
This code makes a function with fun that squares a number, names it square, and calls it with 6. Press Run to see the result.
Why this works
Sometimes a function is only needed for a single call site (as a one-off rule handed to another function) and giving it a permanent name with `let` would just add clutter. `fun params -> body` writes a function without naming it; `let square = fun n -> n * n` then binds that anonymous function to `square` so it can be reused, but you could just as easily pass a `fun ... -> ...` expression directly into another function without ever binding it to a name at all.
Calling an anonymous function bound to a name works exactly like calling any other function, `square 6`, there's no special syntax needed for the call itself, unlike some languages that require a different call syntax for lambdas.