【问题标题】:Adding elements of two lists in haskell [closed]在haskell中添加两个列表的元素[关闭]
【发布时间】:2021-06-07 21:57:18
【问题描述】:

add_lists list1 list2:返回每个列表中相同位置的元素之和作为 新名单。如果一个列表比另一个短,假设较短的列表在 “缺失的地方”。 这是我的haskell 代码:

add_lists list1 list2= if length.list1 < length.list2
                       then list2 ++ [i] && zipWith(+)list1 list2 
                       else zipWith (+) list1 list2
                       where [i|i=0,i=length.list2-length.list1]

我不断收到错误

【问题讨论】:

  • 提示:利用显式递归。
  • 由于缺乏焦点而投票结束。 stackoverflow.com/help/how-to-ask
  • 您的语法错误。 length . list1 将与 list1 函数组成 length 函数,但 list1 不是函数。我不知道你的 where 子句应该做什么,但那是为了绑定一个变量。你有一个看起来像列表理解的东西,但语法都是假的。我无法判断它的正面或反面。
  • @dfeuer:“逐字逐句”阅读。 length.list1 = “长度 of list1”,如head . reverse = “反向头部(列表)”; list2 ++ [i] = “到list2,追加(通过变异)列表 i”; &amp;&amp; = “和(然后)”;并且[i|i=0,i=length.list2-length.list1] 是“列表 i(再次将[] 解释为符号)等于 0(无处不在)并且i 是(在“有”的意义上)长度 list2 减去长度 list1”。
  • 您可以在定义组合器pw f = map f . transpose(其中transpose 来自Data.List)的列表上创建函数的逐点版本。因此,对于这种情况,您可以定义一个更通用的sumPW = pw sum,它对列表列表进行操作。然后add_lists list1 list2 = sumPW [list1, list2].

标签: haskell


【解决方案1】:

使用semialign 包,你可以这样写:

import Data.Align (padZipWith)
import Data.Maybe (fromMaybe)

addLists :: (Semialign t, Num a) => t a -> t a -> t a
addLists = padZipWith (\a b => fromMaybe 0 a + fromMaybe 0 b)

【讨论】:

    【解决方案2】:

    在这里使用显式递归可能是最简单的。

    add_lists [] list2 = list2
    add_lists list1 [] = list1
    add_lists (x:xs) (y:ys) = x + y : add_lists xs ys
    

    【讨论】:

    • 感谢您的绝妙建议,它完美地运行。 @MarkSaving
    【解决方案3】:

    语法

    1. length.list2 中的. 是函数组合运算符,而list2 不是函数,
    2. where i= 会开始定义,而where [i| 不会,
    3. 列表理解中的i= 需要let i= 或i&lt;-,并且
    4. 您的&amp;&amp; 只能组合两个Bool 值。

    您想解决缩短 zipWith

    a +++ b = zipWith (+) a b ++ drop (length b) a ++ drop (length a) b
    

    或构建一个较少丢弃的zipWith 替代方案:

    (a:c) +++ (b:d) = (a+b) : (c +++ d)
    e +++ [] = e
    [] +++ f = f
    

    【讨论】:

    • length 通常被认为是有问题的,因为它不适用于无限列表并且通常会影响性能(内存)。
    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    相关资源
    最近更新 更多