gpt4 book ai didi

haskell - haskell中解压功能的实现

转载 作者:行者123 更新时间:2023-12-03 14:30:51 24 4
gpt4 key购买 nike

我正在尝试实现解压缩功能,我执行了以下代码但出现错误。

myUnzip [] =()
myUnzip ((a,b):xs) = a:fst (myUnzip xs) b:snd (myUnzip xs)

我知道这个问题在第二行的右侧,但我知道如何改进它。
请任何提示。

我得到的错误是
ex1.hs:190:22:
Couldn't match expected type `()' with actual type `[a0]'
In the expression: a : fst (myUnzip xs) b : snd (myUnzip xs)
In an equation for `myUnzip':
myUnzip ((a, b) : xs) = a : fst (myUnzip xs) b : snd (myUnzip xs)


ex1.hs:190:29:
Couldn't match expected type `(t0 -> a0, b0)' with actual type `()'
In the return type of a call of `myUnzip'
In the first argument of `fst', namely `(myUnzip xs)'
In the first argument of `(:)', namely `fst (myUnzip xs) b'

ex1.hs:190:49:
Couldn't match expected type `(a1, [a0])' with actual type `()'
In the return type of a call of `myUnzip'
In the first argument of `snd', namely `(myUnzip xs)'
In the second argument of `(:)', namely `snd (myUnzip xs)'

最佳答案

您可以通过遍历列表两次来效率低下

myUnzip [] = ([], []) -- Defaults to a pair of empty lists, not null
myUnzip xs = (map fst xs, map snd xs)

但这并不是很理想,因为与仅循环一次相比,它肯定会很慢。为了解决这个问题,我们必须递归地进行
myUnzip [] = ([], [])
myUnzip ((a, b):xs) = (a : ???, b : ???)
where ??? = myUnzip xs

我会让你填空,但从这里开始应该很简单,看看 myUnzip 的类型签名并在 where ??? = myUnzip xs 找出你可以用什么代替问号

关于haskell - haskell中解压功能的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com