[英]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.