2015-02-10 148 views
3

我在Haskell中有这样的代码。let在Haskell中的用法

import Data.List 

main = do 
    putStrLn $ "\nVerify if Exists in a String" 
    let wordlist = ["monad", "monoid", "Galois", "ghc", "SPJ"] 
    let tweet = "This is an example tweet talking about SPJ interviewing with Galois" 
    print $ map (flip isInfixOf tweet) wordlist 

没有let,我有这样的错误消息:10_things.hs:16:14: parse error on input ‘=’

这是另一种正常工作的代码。

import Data.List 

wordlist = ["monad", "monoid", "Galois", "ghc", "SPJ"] 
tweet = "This is an example tweet talking about SPJ interviewing with Galois"  
main = do 
    putStrLn $ "\nVerify if Exists in a String" 
    print $ map (flip isInfixOf tweet) wordlist 

在这种情况下,我有错误parse error (possibly incorrect indentation or mismatched brackets)与让。 我的问题是何时何时不在Haskell中使用let

+0

'do'符号并不像它看起来那么容易:HTTP:// en.wikibooks.org/wiki/Haskell/do_notation + http://book.realworldhaskell.org/read/io.html#io.bind – zerkms 2015-02-10 02:11:38

回答

9

声明/方程式需要在里面无论是letwhere块。在模块的顶层不需要let的原因是,它将自己计算为where块,并以其module声明开始。不包含明确的module头模块之初得到一个隐含的

module Main (main) where 

顺便说一句,缩进的let块可以包含多个声明:只要方程垂直排列,代码中不需要第二个let

7

哈斯克尔有两种引入名称的方法:letwhere

只要有正常表达式,就可以使用let。这可以出现在两个地方:如果你定义了一个正常值,并且你是在内部注释。在第一种情况下,你可以使用let ... in只是一个单一的表达式中引入了一个名字:

myFoo = let x = 10^10 in x + x 

里面做,符号,你不需要一个in;相反,let就像一个正常的“声明”中的符号一样占据了一条线。这是你的第一个例子有:

main = do 
    let x = something 
    ... 

的另一种方法介绍名字是where条款,其中去外界表达。程序的顶层(在模块中定义所有全局可见的名称)位于where块中,这就是为什么您只需编写name = expression而不需要let。发生这种情况是因为你的模块隐含地具有

module Main where 

即使你没有自己写。

你也可以写在不同的范围自己的where块,这也让您不let定义名称:

foo x = ... 
    where helperA = something 
     helperB = something 
+1

顶级'where'是如此特别,我讨厌甚至比较它与普通的' where子句。在GADT或封闭类型的家族声明中,类声明中还有'where'和'where'。 – dfeuer 2015-02-10 06:19:12

-2
do notation is for monads. I am guessing you are unclear about monads. 

让我们用里面的符号基本上是有约束力的。在做符号转化为这种形式

do {let x = expression; restofit} ==> let x = expression in do {restofit} 

例如本

do 
line1 <- getLine   -- executes an action 
line2 <- getLine   -- executes an action 
let joined = line1 ++ line2 -- pure calculation; no action is executed 
return joined 

这相当于

let joined = line1 ++ line2 in line1 <-getLine >> line2 <- getLine 
+0

最后一行代码的语法无效。 – 2015-02-11 05:34:58