Haskell:使用(curry snd)计算列表的长度

时间:2017-02-18 09:41:39

标签: list haskell fold curry

我被赋予了使用foldr Haskell函数计算列表长度的赋值,所以我做了这两个例子

flength :: [a] -> Int
flength = foldr (\ _ n -> n+1) 0

flength' :: [a] -> Int
flength' l = foldr aux 0 l
    where
        aux _ n = n+1

然后,作为个人挑战,教授要求我们使用snd功能,昨天我想出了这个:

flength'' :: [a] -> Int
flength'' = foldr ((+1).(curry snd)) 0

我想要发生的是,此功能会将列表h和累加器0的头部转换为(h,0)对,然后返回0,之后将其应用于函数(+1)

我希望这可以递归完成,有效地在最后给出了列表的长度。

相反,我收到此错误消息:

    [1 of 1] Compiling Main             ( f1.hs, interpreted )

f1.hs:54:24: error:
    * No instance for (Num (Int -> Int))
        arising from an operator section
        (maybe you haven't applied a function to enough arguments?)
    * In the first argument of `(.)', namely `(+ 1)'
      In the first argument of `foldr', namely `((+ 1) . (curry snd))'
      In the expression: foldr ((+ 1) . (curry snd)) 0 xs
Failed, modules loaded: none.

为什么会发生这种情况?如何才能使此代码生效?

1 个答案:

答案 0 :(得分:3)

让我们把所有工具摆在我们面前,就像一位优秀的工匠一样:

foldr :: (a -> b -> b) -> b -> [a] -> b
snd   :: (a, b) -> b

首先,我们注意到sndfoldr并不适合。所以,让我们像你一样使用curry,并将curry snd添加到我们的小工具库中:

foldr     :: (a -> b -> b) -> b -> [a] -> b
curry snd ::  a -> b -> b

这看起来非常很有希望。现在我们需要将1添加到curry snd的结果中,否则我们只需要编写flip const。让我们从lambda开始:

\a b -> 1 + curry snd a b
= \a b -> ((+1) . curry snd a) b

我们现在可以推送b并最终以

结束
\a -> (+1) . curry snd a
= \a -> (.) (+1) (curry snd a)
= \a -> ((.) (+1)) (curry snd a)
= \a -> (((.) (+1)) . curry snd) a

现在我们也可以从两边逐渐减少a并最终获得

(((.) (+1)) . curry snd) = ((+1) . ) . curry snd

因此,您的第三个变体是

flength'' = foldr (((+1) . ) . curry snd) 0

现在,您为什么收到错误消息?您与(+1) . curry snd关系密切,但类型无效:

(+1)      :: Int -> Int
--            v                    v
(.)       :: (b ->  c)    -> (a -> b       ) -> a -> c
curry snd ::                  t -> (x -> x)
              ^                     ^

但在您的情况下,b签名中的(.) s不匹配。其中一个是Int,另一个是函数。

TL; DR :如果您想免费写f (g x y),请写((f.) . g)

相关问题