簡體   English   中英

Haskell函數應用程序

[英]Haskell Function Application

有點新手問題,但我在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的行為有何不同?

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'的定義一致。

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

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

可能會幫助你了解發生了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM