【问题标题】:Haskell how to append with custom dataHaskell如何附加自定义数据
【发布时间】:2021-05-20 08:13:19
【问题描述】:

我有一个如下的数据声明

data List a = Nil | Cons a (List a)

nil 表示空列表,否则表示非空列表

这个自定义数据类型明显不支持(:),如果没有(++),这个数据类型怎么追加2个List呢?

函数类型如下

append :: List a -> List a -> List a

我从这样的事情开始

app Nil xs = xs
app (Cons x xs) ys = 

【问题讨论】:

    标签: haskell


    【解决方案1】:

    这个自定义数据类型显然不支持(:)

    (:) 数据构造函数在这里是Cons,但ConsList a 的影响与(:)[a] 的影响相同(或更规范的[] a)。因此,您已经有了一个函数,您可以在其中使用 a 代表 List a

    如何在没有(++) 的情况下将这种数据类型的 2 个列表附加在一起?

    使用递归。如果第一个列表用尽,则返回第二个列表,如果第一个列表有Cons … …,则需要返回Cons,其中第一项是左侧列表的第一项,尾部是结果的第一个参数的尾部使用递归。因此,这将如下所示:

    app :: List a -> List a -> List a
    app Nil xs = xs
    app (Cons x xs) ys = Cons x …

    我把实现 作为练习。

    【讨论】:

      【解决方案2】:

      我们其实可以从数据定义和一些常识/append必须遵守的一些规律推导出函数定义。

      首先,我们有

      data List a = Nil | Cons a (List a)
      
      append :: List a -> List a -> List a
      
      --        Nil         Nil         Nil
      --       Cons x xs   Cons y ys   Cons z zs
      

      这意味着我们可以枚举所有可能的 2 x 2 x 2 情况,

      append Nil         Nil         = Nil
      append Nil         Nil         = Cons z zs   where z = .... ; zs = ....
      append Nil         (Cons y ys) = Nil
      append Nil         (Cons y ys) = Cons z zs   where z = .... ; zs = ....
      append (Cons x xs) Nil         = Nil
      append (Cons x xs) Nil         = Cons z zs   where z = .... ; zs = ....
      append (Cons x xs) (Cons y ys) = Nil
      append (Cons x xs) (Cons y ys) = Cons z zs   where z = .... ; zs = ....
      

      然后删除那些完全没有意义的方程式,并完成那些有意义的方程式。

      追加法则很简单,不言而喻用一些伪代码写出来就足够了,

         append [x1,x2,....,xn] [y1,y2,....,ym] =
                [x1,x2,....,xn,  y1,y2,....,ym]
      

      这就像说什么新鲜事。

      【讨论】:

        猜你喜欢
        • 2011-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-24
        • 1970-01-01
        • 2018-07-24
        • 2011-07-20
        • 2021-06-10
        相关资源
        最近更新 更多