簡體   English   中英

Haskell 嵌套 where 子句

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM