gpt4 book ai didi

haskell - 如何返回Haskell编程中交替组合两个函数列表所产生的函数?

转载 作者:行者123 更新时间:2023-12-02 21:18:08 25 4
gpt4 key购买 nike

在我的 Haskell 类(class)作业中,我想要应对一个挑战,本质上是了解如何处理函数列表。输入由两个这样的列表组成,假设第一个列表为 [A0..AN],第二个列表为 [B0..BN]。我需要返回一个由应用它们的函数组成的函数,以便函数在输出函数内交替作为嵌套函数参数。事实上,这意味着输出如下:

G x = A0 (B0 (A1 (B1 (A2 (B2 (...AN (BN))))))

我的主要解决方案不起作用,我尝试从以下代码开始:

funcCarnage :: [a -> a] -> [a -> a] -> (a -> a)
funcCarnage (x:xs) (y:ys) = extraFuncCarnage xs ys x 2 where
extraFuncCarnage bs fs gs n
| length bs == 0 && length fs == 0 = gs
| odd n = extraFuncCarnage (tail bs) fs (gs $ head bs) (n + 1)
| otherwise = extraFuncCarnage bs (tail fs) (gs $ head fs) (n + 1)

编译失败并出现错误消息:

* Occurs check: cannot construct the infinite type: a ~ a -> a
Expected type: a -> a
Actual type: (a -> a) -> a -> a
* In the expression: extraFuncCarnage xs ys x 2
In an equation for `funcCarnage':
funcCarnage (x : xs) (y : ys)
= extraFuncCarnage xs ys x 2
where
extraFuncCarnage bs fs gs n
| length bs == 0 && length fs == 0 = gs
| odd n = extraFuncCarnage (tail bs) fs (gs $ head bs) (n + 1)
| otherwise = extraFuncCarnage bs (tail fs) (gs $ head fs) (n + 1)

* Occurs check: cannot construct the infinite type: t1 ~ t -> t1
Expected type: [t] -> [t] -> t1 -> a1 -> t -> t1
Actual type: [t] -> [t] -> (t -> t1) -> a1 -> t -> t1
* In an equation for `funcCarnage':
funcCarnage (x : xs) (y : ys)
= extraFuncCarnage xs ys x 2
where
extraFuncCarnage bs fs gs n
| length bs == 0 && length fs == 0 = gs
| odd n = extraFuncCarnage (tail bs) fs (gs $ head bs) (n + 1)
| otherwise = extraFuncCarnage bs (tail fs) (gs $ head fs) (n + 1)

这是一些晦涩的投诉,所以我很困惑如何继续解决。我该如何修复这两种类型错误?

最佳答案

您可以先合并两个列表,然后进行右折叠。

import Control.Applicative(ZipList(..))

funcCarnage fs gs = foldr (.) id list
where
list = concat $ getZipList $ (\x y -> [x, y]) <$> ZipList fs <*> ZipList gs

关于haskell - 如何返回Haskell编程中交替组合两个函数列表所产生的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59834894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com