While studying for a Functional Programming exam, I came across the following question from a previous test:
t1 = (reverse . take 2 . words . \ _ -> name)"!"
The task is to write the output of the statement. The variable name refers to the student’s name, written in the form “Smith, John”. If I enter the statement into WinHugs, I get the following output:
["John","Smith,"]
I understand what the functions reverse, take and words are doing and I understand how the . operator connects them. What I don’t understand is what is happening here:
\ _ -> name
What are the slash, underscore and “arrow” for? Also, what does the exclamation point in quotation marks do? (nothing?)
It’s a lambda function that discards its (only) argument (i.e. “!”) and yields
name.As another lambda example, the following would be a lambda function that squares its argument:
The
\is the notation used to introduce a lambda function.The
_means “variable about whose name we do not care”.The
->separates the lambda function’s arguments from the expression used to specify its result.