[英]Haskell nested where clauses
我是 Haskell 的初学者编码员,在做这本神奇书的第一章的练习时: http : //book.realworldhaskell.org/read/getting-started.html我遇到了这个问题:
-- test comment
main = interact wordCount
where
wordCount input = show (ls ++ " " ++ ws ++ " " ++ cs ++ "\n")
where
ls = lines input
ws = length words input
cs = length input
wonderbox:ch01 manasapte$ runghc WC < quux.txt
WC.hs:5:9: parse error on input ‘where’
为什么我不能嵌套我的 wheres ?
由于您的第二个where
附加到wordCount
定义,因此它需要缩进更多。 (尽管之后您仍然会遇到其他一些错误。)
其他人已经回答了。 我将添加一些更多的解释。
稍微简化一下,Haskell 的缩进规则是:
where
, let
, do
, case ... of
)。因此,
where
wordCount input = show (ls ++ " " ++ ws ++ " " ++ cs ++ "\n")
where
ls = lines input
ws = length words input
cs = length input
其实意思是
where {
wordCount input = show (ls ++ " " ++ ws ++ " " ++ cs ++ "\n")
;
where { -- same column, new entry
ls = lines input
; -- same column, new entry
ws = length words input
; -- same column, new entry
cs = length input
}
}
它将第二个where
作为与wordCount
无关的单独定义。 如果我们缩进更多,它将起作用:
where {
wordCount input = show (ls ++ " " ++ ws ++ " " ++ cs ++ "\n")
where { -- after the pivot, same entry
ls = lines input
;
ws = length words input
;
cs = length input
}
}
缩进不正确,这是工作版本:
-- test comment
import Data.List
main = interact wordCount
where wordCount input = unlines $ [concat $ intersperse " " (map show [ls, ws, cs])]
where ls = length $ lines input
ws = length $ words input
cs = length input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.