2015-02-10 119 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