【问题标题】:Want to add to a data type in Haskell想要添加到 Haskell 中的数据类型
【发布时间】:2015-11-17 13:12:07
【问题描述】:

嗨,我有一个数据类型是

data MyIntStr = MyIntStr { intList :: IntList, strList :: StrInt}
type IntList = [[Int]]
type StrList = [[String]]

我想在MyDataintListstrList 中添加一些东西。所以我传递了一个空的默认数据,然后尝试将 Ints 添加到Intlist

putInts :: [Int] -> MyIntStr -> MyIntStr
putInts (h:t) d
    |length t /= 0 = putInts t (intList:h)
    |otherwise intList:h

这给出了错误任何想法如何做到这一点?

【问题讨论】:

  • 1. data 是一个关键字。您不能将其用作变量的名称。 2.intList 的类型为MyData -> IntList
  • @chi 太没用了
  • @NeoStreets 这将是长期的。
  • @NeoStreets chi 的目标差不多,但还是有一些代码:putInts is d = d { intList = intList d ++ is }

标签: list haskell types functional-programming


【解决方案1】:

只是以一些建设性的帮助(或者我希望如此)来结束这件事,这里有一个版本应该可以满足您的期望:

type IntList = [Int]
type StrList = [String]

data MyIntStr = MyIntStr { intList :: IntList, strList :: StrList }
              deriving Show

empty :: MyIntStr
empty = MyIntStr [] []

putInts :: [Int] -> MyIntStr -> MyIntStr
putInts is (MyIntStr is' ss) = MyIntStr (is'++is) ss

这是一个例子:

λ> putInts [1,2,3] empty
MyIntStr {intList = [1,2,3], strList = []}

我做了什么:

  • 添加了deriving Show,这样我就可以看到我的示例了;)
  • StrInt 更改为StrList,因为你显然是故意的
  • 添加了empty,以便我可以测试
  • 使用模式匹配重写 putInts++ 以连接您的 [Int] 列表

【讨论】:

  • 谢谢,我明白他的意思,但我理解基本原理,这是让生活变得艰难的最后一步
猜你喜欢
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
相关资源
最近更新 更多