繁体   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