2014-11-04 51 views
2

我想創建一個顯示列表的最後一個元素的函數。 這是我的代碼:GHCi函數中的非窮舉模式

ghci> let myLast :: [a] -> a 
ghci> let myLast [] = error 
ghci> let myLast [x] = x 
ghci> let myLast (x:xs) = myLast xs 

而且我得到以下錯誤:

***Exception: Non-exhaustive patterns in function myLast 

我明白,你當你缺少的情況下,這個錯誤,但我想我已經包括了所有可能性。有任何想法嗎?

回答

5

如果在每一行使用let,每個定義將命名爲myLast一個功能,陰影之前的所有定義。所以你最終相當於

GHCi> let myLast (x:xs) = myLast xs

孤單。

你可能想是什麼力量讓一個Haskell文件,說MyLast.hs,含

module MyLast where 

myLast :: [a] -> a 
myLast [] = error 
myLast [x] = x 
myLast (x:xs) = myLast xs 

可以然後將該文件加載到GHCI與ghci MyLast.hs

的關鍵字時,你已經在GHCI(或者,在一些單子像IO,或在其他功能),並希望做出局部定義只需要let。但是,您只能使用let一次,例如

GHCi> let myLast :: [a]->a; myLast [] = error; myLast [x] = x; myLast (x:xs) = myLast xs

twiceLast :: [Int] -> [Int] 
twiceLast = let myLast [] = error 
       myLast [x] = x 
       myLast (x:xs) = myLast xs 
      in \xs -> 2 * last xs 

我會,但是,喜歡寫爲

twiceLast = (2*) . myLast 
where myLast [] = error 
     myLast [x] = x 
     myLast (x:xs) = myLast xs 
2

在ghci中的let每次使用引入了一個新的定義,讓你重新定義你的功能多而不是增加案例。

兩種選擇:

  • 發生在一個文件中的定義,並與:r命令
  • 使用:{ ... :}加載它進入多行:

例如爲:

*Main> :{ 
*Main| let foo [] = True 
*Main|  foo _ = False 
*Main| :} 
*Main>