代码之家  ›  专栏  ›  技术社区  ›  Steve B.

Haskell函数的应用

  •  20
  • Steve B.  · 技术社区  · 16 年前

    有点像新手哈斯克尔的问题,但我在哈斯克尔的书中遇到了这个例子 tutorial examples . 对于“查找列表的最后一个元素”,有一些明显的版本,如

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

    但我无法理解另一个版本:

    myLast' = foldr1 (const id)
    

    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的函数吗?或者,函数order making(const id)的行为与const有何不同?

    2 回复  |  直到 16 年前
        1
  •  31
  •   Charles Duffy    15 年前

    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' .

        2
  •  9
  •   Magnus    16 年前

    我严重依赖于 :t 在试图理解哈斯克尔的时候。在这种情况下:

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

    也许能帮你看看发生了什么。