"I got stuck while parsing the function definition:": 如何正确定义 Elm 函数?

"I got stuck while parsing the function definition:": How to properly define an Elm function?

我是第一次使用 Elm experiment/practicing,运行 在定义函数时遇到了困难。以下:

isDivisible : Int -> Int -> Int -> Bool
isDivisible n x y =
  ((modBy n x) == 0) && ((modBy n y) == 0)

isDivisible 4 4 2

结果:

-- PROBLEM IN DEFINITION --------------------------------------- Jump To Problem

I got stuck while parsing the `isDivisible` definition:

5| isDivisible 4 4 2
                    ^
I am not sure what is going wrong exactly, so here is a valid definition (with
an optional type annotation) for reference:

    greet : String -> String
    greet name =
      "Hello " ++ name ++ "!"

Try to use that format!

CodeWars 使用的 Elm 解释器让这个通过;它只是说某些输入的输出不正确(例如 4 4 2)。 "I got stuck while parsing the * definition:" 没有 Google 结果(即使解析器是开源的,请看图)。这是我第一次使用函数式语言。怎么了?

我不确定为什么你的 isDivisible 函数需要三个数字,但你看到的语法错误不是指它的定义,而是指你的调用:

isDivisible 4 4 2

在 Elm 中,您所有的表达式(如上面的表达式)都需要存在于函数中。您不能简单地将它们写在文件的顶层。它们需要在 Elm 知道如何处理它们的上下文中使用。

Elm 程序从 main 函数开始执行。 main 函数可能会 return 不同的东西,这取决于你想做什么,但最简单的用例是 return 一些 HTML。

module Main exposing (main)

import Html exposing (text)


main =
    text "Hello World"

Run in ellie

如果您在浏览器中编译并打开它,您将在屏幕上看到文本 "Hello World"。请注意,我们将代码放在 main 函数下,而不是直接将它们写入文件中。

考虑到这一点,您可以执行类似以下操作来显示调用的输出:

main =
    if isDivisible 4 4 2 then
        text "It is divisible"

    else
        text "It is NOT divisible"

Run in ellie

如果您只想在控制台中查看调用的输出,您可以使用 Debug.log 函数,如下所示:

main =
    let
        _ =
            Debug.log "Is divisible?" (isDivisible 4 4 2)
    in
    text "Hello World"

Run in Ellie(见日志)