All lessons

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

OCaml · Power Tools: Anonymous Functions, List.map & the Pipe Operator0/5 cleared

Enemy 1 of 5

Anonymous functions with fun

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.

You
Binary Treant

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 36