【问题标题】:Where is the indentation/layout error in my Haskell code?我的 Haskell 代码中的缩进/布局错误在哪里?
【发布时间】:2020-07-25 03:30:25
【问题描述】:

我正在尝试在 Haskell 中为我大学的一门课完成一项简单的家庭作业,但我不知道为什么我的代码无法编译:

-- Comments
module Main where

main :: IO ()
main = do
  n <- readLn
  print (fac n)
  print (facList n)
  print (sumFacs n)
  print (fibonacci n)

-- Aufgabe 2 (a):
fac :: Int -> Int
let
  fac 0 = 1
  fac i = i * fac(i - 1)

-- Aufgabe 2 (b):
facList :: Int -> Int -> [Int]
let
  facList x y = [fac m | m <- [x..y]]

sumFacs :: Int -> Int -> Int
let
  sumFacs x y = sum (facList x y)

-- Aufgabe 3:
fibonacci :: Int -> Int
let
  fibonacci 0 = 1
  fibonacci 1 = 1
  fibonacci i = fibonacci (i - 1) + fibonacci (i - 2)

当我尝试使用 Glasgow 编译器编译上述代码时,我收到以下错误消息:

Uebung01.hs:19:1: error:
    parse error (possibly incorrect indentation or mismatched brackets)
   |
19 | facList :: Int -> Int -> [Int]
   | ^

所有功能都在交互模式下工作。很抱歉发布这么简单的问题,但我对 Haskell 完全陌生,并且真的很难理解空格规则是如何工作的。我已经查看了类似问题的答案,但我仍然无法找到我的错误。感谢阅读。

【问题讨论】:

    标签: haskell syntax parse-error


    【解决方案1】:

    let block [Haskell-report] 需要 in 来指定表达式。在您的fac 函数中,您定义了一个let 块,但没有in,它用于定义您可以在in 子句中使用的局部范围变量。但是,您在这里需要let,您可以将fac 定义为:

    fac :: Int -> Int
    fac 0 = 1
    fac i = i * fac (i - 1)
    

    您需要以类似的方式重构其他功能。

    【讨论】:

    • 值得注意的例外情况:在 GHCi 和 do 块中,let 没有 in 很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    相关资源
    最近更新 更多