2008-12-05 158 views
20

有點新手haskell的問題,但我在Haskell的tutorial examples中遇到了這個例子。對於「查找列表的最後一個元素」,也有一些明顯的版本,像Haskell函數應用

last' [x] = x 
last' (_:xs) = last' xs 

但我不能讓另一個版本的意義提出:

myLast' = foldr1 (const id) 

因此,在努力使什麼樣的ID功能的應用程序在做的意義,我想在ghci的:

const id 1 2 -> gives 2 

這種結合是這樣的:

(const id) 1 2 -> gives 2 

,而不是像這樣:

const (id 1) 2 -> gives 1 

但我不會做的這個意義。 (const id)應該轉化爲類似

`(\x y->x) (\x->x)` 

不應該在該返回只返回第一個元素的ID的功能?或者,函數順序製作(const id)的行爲與const的行爲有什麼不同?

+1

歡迎來到10k俱樂部! – 2010-01-28 21:05:44

+3

我想感謝學院,我的製作人,導演...... – 2010-01-28 21:08:43

+0

loooooooool!喜歡:P – Nomics 2011-12-13 13:40:58

回答

30

const定義是

const x = \_ -> x 

因此,(const id)是一個函數,它有一個參數,並始終返回id

const id 1 2 = (\_ -> id) 1 2 
      = id 2 
      = 2 

foldr1定義是

foldr1 f [x] = x 
foldr1 f (x:xs) = f x (foldr1 f xs) 

如果我們有

myLast' = foldr1 (const id) 

然後

myLast' [x] = foldr1 (const id) [x] 
       {- definition of foldr1 -} 
      = x 

myLast' (x:xs) = foldr1 (const id) (x:xs) 
       {- definition of foldr1 -} 
       = (const id) x (foldr1 (const id) xs) 
       {- definition of const -} 
       = (\_ -> id) x (foldr1 (const id) xs) 
       {- function application -} 
       = id (foldr1 (const id) xs) 
       {- definition of id -} 
       = foldr1 (const id) xs 
       {- definition of myLast' -} 
       = myLast' xs 

與的last'定義一致。

9

當試圖理解Haskell時,我非常依賴:t。在這種情況下:

Prelude> :t const id 
const id :: b -> a -> a

可能幫助您瞭解發生了什麼事情。