在Elm中使用命名函数声明而不是匿名函数

时间:2017-10-04 18:08:09

标签: elm

在REPL中,如果我使用

> String.filter (\char -> char /= '-') "800-555-1234"

我得到了结果:

"8005551234" : String

正如所料。

但是如果不使用匿名函数,我会使用这样的命名函数声明:

> String.filter (isKeepable char = char /= '-') "800-555-1234"

我收到此错误:

-- SYNTAX PROBLEM -------------------------------------------- repl-temp-000.elm

The = operator is reserved for defining variables. Maybe you want == instead? Or
maybe you are defining a variable, but there is whitespace before it?

3|   String.filter (isKeepable char = char /= '-') "800-555-1234"
                                    ^
Maybe <http://elm-lang.org/docs/syntax> can help you figure it out.

这对我来说似乎很奇怪,因为函数声明本身是一个返回函数对象的表达式:

> isKeepable char = char /= '-'
<function> : Char -> Bool

那么,为什么不能将该函数引用传递给filter,就像任何求值为函数的表达式一样?

1 个答案:

答案 0 :(得分:4)

命名函数声明仅在顶级或let子句中有效。试试这个:

> let isKeepable char = char /= '-' in String.filter isKeepable "800-555-1234"
相关问题