Haskell
split:: [(a,b)] -> ([a],[b])
功能应该返回
split [(1,’a’), (2,’b’), (3,’c’)] = ([1,2,3], "abc")
请问如何使用列表理解来做到这一点?感谢
答案 0 :(得分:5)
您正在寻找的拆分功能已存在于标准Haskell Prelude库中;它被称为解压缩。
使用列表推导:
split xs = ([a | (a,_) <- xs], [b| (_,b) <- xs])
答案 1 :(得分:2)
虽然你得到了正确答案,但这是一种更系统地解决问题的方法。
如果你将问题分解为
你得到了
firsts xs = [a | (a, _) <- xs]
seconds xs = [b | (_, b) <- xs]
split xs = (firsts xs, seconds xs)
然后你可以&#34;内联&#34;辅助功能
split xs = ([a | (a, _) <- xs], [b | (_, b) <- xs])