在 Elm-Lang 中,\_ -> 语句(符号、运算符、模式)是什么意思?

In Elm-Lang what does the \_ -> statement (symbol, operator, pattern) mean?

我发现了我认为是 test code 中的模式。 乍一看,这是我从未见过的模式,但它到底是什么?

我正在为可能 运行 遇到同一问题的人们添加此条目。

\_ -> 是一个接受一个参数的匿名函数,但它不会在函数体中使用该参数,因此与其将其命名为 \a -> 只是使用 [= 丢弃参数12=].

实际上不是模式,而是lambda(匿名函数,未绑定到标识符的函数定义。)正如 megapctr 在 elm slack group.

向我指出的那样

我在这个 context:

中找到了这个 lambda
unstyledDiv : Test
unstyledDiv =
    let
        input =
            Fixtures.unstyledDiv

        output =
            ""
    in
        describe "unstyled div"
            [ test "pretty prints nothing, because the stylesheet had no properties." <|
                \_ ->
                    prettyPrint input
                        |> Expect.equal (output)
            ]

所以为了更好地理解这个 lambda 在这种情况下是如何工作的。我使用 elm-repl 编写了我的 lambda (\_ -> "helloWorld")。

(\_ -> "helloWorld") 5
(\_ -> "helloWorld") 4.0
(\_ -> "helloWorld") "abalone"
(\_ -> "helloWorld") not
(\_ -> "helloWorld") abs

输出:"helloworld" :String

所有产生相同的输出:‖"helloworld" :String 用于任何类型的输入,IntFloat, 字符串, 函数.

然后模拟与我使用管道传输的测试代码相同的格式,<|,lambda 到身份函数,这应该导致相同的输出:"helloworld"

identity <| (\_ -> "helloWorld") "anything"

输出:"helloworld" :String

为了更接近测试代码片段,我做了以下操作

(identity <| (\_ -> "helloworld" ) "anything") |> String.reverse

输出:"dlrowolleh" : String

我希望这能帮助那些第一次看到这样的代码片段时可能感到困惑的人。

另一个类似的例子

\( ) -> 语句

无参数/“无命名参数本机类型”Lambda

不带参数的 lambda: \() -> "hellouniverse"

(\() -> "hellouniverse") ()

输出:“hellouniverse”:字符串

(identity <| (\() -> "helloworld" ) ()) |> String.reverse

输出:“esrevinuolleh”:字符串

如果你试图传递除()以外的参数,单位,例如StringInt or Float, or Function 会导致编译错误.

错误如下:

传递一个Int的例子,5

==================================== ERRORS ====================================

-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

The argument to this function is causing a mismatch.

4|    \() -> "hellouniverse" ) 5
                               ^
This function is expecting the argument to be:

    ()

But it is:

    number

传递函数、身份

的示例
==================================== ERRORS ====================================

-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

The argument to this function is causing a mismatch.

4|    \() -> "hellouniverse" ) identity
                               ^^^^^^^^
This function is expecting the argument to be:

    ()

But it is:

    a -> a

演示使用 No Arg lambda:

定义测试如下:

test x = 
   ((++) "super  "  <|  ( (\() -> "hellouniverse" ) <| x )) |>  String.reverse

然后应用函数只需传递单位符号,():

test ()

输出:“esrevinuolleh repus”:String