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

Haskell函数应用程序

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

    这有点像haskell的新手问题,但我在haskell tutorial examples 对于“查找列表的最后一个元素”,有一些明显的版本,比如

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

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

    定义 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 当试图理解Haskell时。在这种情况下:

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

    可能会帮助你看到发生了什么。

    推荐文章