2

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?)

4 Answers 4

7

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:

\x -> x * x

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good explanation. I am still somewhat confused by the exclamation mark though. Do you want to say that in this case the exclamation mark is added only for obfuscation?
The "!" is the value that is being ignored. The exclamation mark is just a character in a string that's being ignored: ignore it.
5

What you are seeing there is an anonymous function, or lambda function (that name comes from lambda calculus). The backslash tells you that you are starting the function. The underscore says that the function takes one argument and ignores it. The arrow points from the argument list to the result - in this case, it ends up ignoring its argument and returning the name. Essentially, \_ -> name is the same as const name.

Comments

3

A constant anonymous function: which ever the argument, return name.

Haskell's lambda expressions (i.e. anonymous functions) come in this form:

\x -> f x

where x is an argument, and f x an expression using this argument. The special variable _ matches anything and treats it as unimportant.

Comments

2

The "slash" is part of a lambda function, the underscore is a "wildcard" used in patterns (it is discarded). The arrow is another part of the lambda function. The function \ _ -> name returns the name, regardless of input, so the "!" does nothing but provide (unused) input to the function.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.