在haskell中实现解压缩函数 [英] implementation of unzip function in haskell

查看:65
本文介绍了在haskell中实现解压缩函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  myUnzip [] => 

我试图实现unzip函数,我做了下面的代码,但是出现错误。 ()
myUnzip((a,b):xs)= a:fst(myUnzip xs)b:snd(myUnzip xs)

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



我得到的错误是

  ex1.hs:190:22:
实际类型为[[a0]'
的预期类型'()'无法匹配表达式:a:fst(myUnzip xs)b :snd(myUnzip xs)
在等式'myUnzip'中:
myUnzip((a,b):xs)= a:fst(myUnzip xs)b:snd(myUnzip xs)


ex1.hs:190:29:
实际类型为`()'的
无法匹配预期类型`(t0 - > a0,b0)' 'myUnzip'的返回类型
在`fst'的第一个参数中,即`(myUnzip xs)'
在`(:)'的第一个参数中,即`fst(myUnzip xs)b'

ex1.hs:190:49:
与实际类型`()'
无法匹配预期类型`(a1,[a0])'在`myUnzip'调用的返回类型中
在`snd'的第一个参数中,即`(myUnzip xs)'
在'(:)'的第二个参数中,即`snd myUnzip xs)'


解决方案
  myUnzip [] =([],[])您可以低效地做到这一点 - 默认为一对空列表,不为空
myUnzip xs =(map fst xs,map snd xs)

但是这并不是很理想,因为与仅循环一次相比,它肯定会很慢。为了解决这个问题,我们必须递归地做到这一点

  myUnzip [] =([],[])
myUnzip((a,b):xs)=(a:???,b:???)
其中??? = myUnzip xs

我会让你填写空格,但从这里应该很简单,只要看看 myUnzip 的类型签名,并找出可以代替处的问号的地方。 = myUnzip xs


I am trying to implement the unzip function, I did the following code but I get error.

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

I know that problem is in the right side of the second line but I do know how to improve it . any hint please .

the error that I am getting is

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)'

解决方案

You could do it inefficiently by traversing the list twice

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

But this isn't very ideal, since it's bound to be quite slow compared to only looping once. To get around this, we have to do it recursively

myUnzip [] = ([], [])
myUnzip ((a, b):xs) = (a : ???, b : ???)
    where ??? = myUnzip xs

I'll let you fill in the blanks, but it should be straightforward from here, just look at the type signature of myUnzip and figure out what you can possible put in place of the question marks at where ??? = myUnzip xs

这篇关于在haskell中实现解压缩函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆