Haskell: function composition with anonymous/lambda function

感情迁移 提交于 2019-12-12 18:40:17

问题


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


回答1:


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.




回答2:


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.




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




回答4:


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.



来源:https://stackoverflow.com/questions/11124354/haskell-function-composition-with-anonymous-lambda-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!