【问题标题】:Undestanding how cartesian product implementation on Haskell works了解 Haskell 中的笛卡尔积实现是如何工作的
【发布时间】:2012-11-18 08:42:07
【问题描述】:

我已经开始学习 Haskell,但我无法理解列表列表的笛卡尔积如何工作

这是假定的代码

cprod = foldr f [[ ]]
      where f xs yss = foldr g [ ] xs
            where g x zss = foldr h zss yss
                  where h ys uss = (x : ys) : uss

我没有得到的是最后一个函数 据我所知,我已经替换了变量名

mycart = foldr f [[]]
    where f currentresult listelem = foldr g [] currentresult
          where g currentresultonstep currentresultelem = foldr h currentresultelem listelem
                where h currentresultelemonstep onelistelem = (currentresultonstep:currentreslteleemonstep):onelistelem

最后一个字符串不应该是这样的吗?

where h currentresultelemonstep onelistelem = (onelistelem:currentresultelemonstep):currentresultonstep

当我们尝试将列表的元素添加到当前结果元素的开头时 ?

【问题讨论】:

    标签: haskell cartesian-product


    【解决方案1】:

    首先,您编写的代码在语法上无效:

    foo.hs:3:13: parse error on input `where'
    

    其次,您似乎对foldr的第一个参数中的参数顺序感到困惑:

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

    第一个参数 (a) 是输入列表 ([a]) 的一个元素,第二个参数 (b) 是累加器。

    【讨论】:

    • 当我写'where f x y'时,对于 foldr ,y - 是累加器?
    • 是的,x是当前元素。
    • 因为 foldl 正好相反。
    猜你喜欢
    • 2015-09-06
    • 2012-04-24
    • 2011-09-18
    • 2016-05-07
    • 2013-05-26
    • 2011-05-06
    • 2015-12-05
    • 2016-02-15
    • 2013-12-29
    相关资源
    最近更新 更多