2011-01-11 51 views
3

我寫了下面的解決方案,第10題(99 questions) in Haskell讓語法在Haskell

{-- using dropWhile and takeWhile --} 
enc :: (Eq a) => [a] -> [(Int, a)] 
enc [] = [] 
enc (x:xs) = (length $ takeWhile (==x) (x:xs), x) : enc (dropWhile (==x) xs) 

我想重寫相同的解決方案,但使用了一個讓語法這段時間。

{-- using dropWhile and takeWhile/more readable --} 
enc' :: (Eq a) => [a] -> [(Int, a)] 
enc' [] = [] 
enc' (x:xs) = let num = length $ takeWhile (==x) (x:xs) 
     rem = dropWhile (==x) (x:xs) 
     in (num, x) : enc' rem 

第二個例子不起作用。錯誤是:

*Main> :l Problem10.hs 
Compiling Main    (Problem10.hs, interpreted) 

Problem10.hs:16:38: parse error on input `=' 
Failed, modules loaded: none. 

其中第16行是這個:rem = dropWhile (==x) (x:xs)

有什麼建議? LE:是的,這是一個縮進問題。看來我的編輯器(Notepad ++)應該配置一點,以避免這樣的問題。

+3

難道這是一個縮進錯誤?您可能需要在let語句向前匹配後再推行其餘行。不知道這是不是罪魁禍首。 – templatetypedef 2011-01-11 09:32:34

回答

7

正如已經提到的那樣,這是一個縮進問題,它起始於rem的行不會被縮進,因此它不會被解析爲屬於之前的let語句。確定如何在Haskell中縮進的一種好方法是從Real World Haskell開始的offside rule

而且它往往是一個let陳述開始你的功能時,這樣可以避免寬的壓痕下降到一個新的生產線,像這樣的好主意:

enc :: (Eq a) => [a] -> [(Int, a)] 
enc []  = [] 
enc (x:xs) = 
    let num = length . takeWhile (==x) $ x:xs 
     rem = dropWhile (==x) (x:xs) 
    in (num, x) : enc rem 
4

由於@templatetypedef指出,它確實是的縮進。 rem =需要與num =對齊。