List 要添加到Haskell中的数据类型吗
嗨,我有一个数据类型是List 要添加到Haskell中的数据类型吗,list,haskell,types,functional-programming,List,Haskell,Types,Functional Programming,嗨,我有一个数据类型是 data MyIntStr = MyIntStr { intList :: IntList, strList :: StrInt} type IntList = [[Int]] type StrList = [[String]] 我想在MyData中的intList和strList中添加一些东西。因此,我正在传递一个默认数据,该数据为空,然后尝试将int添加到Intlist: putInts :: [Int] -> MyIntStr -> MyIntStr
data MyIntStr = MyIntStr { intList :: IntList, strList :: StrInt}
type IntList = [[Int]]
type StrList = [[String]]
我想在MyData
中的intList
和strList
中添加一些东西。因此,我正在传递一个默认数据,该数据为空,然后尝试将int添加到Intlist
:
putInts :: [Int] -> MyIntStr -> MyIntStr
putInts (h:t) d
|length t /= 0 = putInts t (intList:h)
|otherwise intList:h
这给了错误一些如何做到这一点的想法?仅以一些建设性的帮助(或者我希望是这样)来结束这一点,这里有一个版本,它应该做你所期望的:
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 = []}
我所做的:
- 添加了
,以便我可以看到我的示例;)李>派生显示
- 将
更改为StrInt
,因为您显然是有意的StrList
- 添加了
,以便我可以测试empty
- 使用模式匹配和
重写++
以连接putInts
列表[Int]
intList
的类型是MyData->intList
@chi,这令人难以置信unhelpful@NeoStreets这将是长期的。@NeoChi的目标非常接近,但还是有一些代码:putInts is d=d{intList=intList d++is}
。谢谢我明白了他的意思,但我明白这其中的基本原理,那就是迈出最后一步,让生活变得艰难