haskell foldr与列表操作 [英] haskell foldr manipulation with lists

查看:155
本文介绍了haskell foldr与列表操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个负数和负数序列的列表,我怎样才能使用foldr将它们分成负数和负数的序列?

例如[1,2 ,3,-1,-2,-3,1,2,3]我会得到[[1,2,3],[ - 1,-2,-3],[1,2,3]]



有些怀疑

我如何知道以前的分区,如果是相同的符号作为我比较当前的?

如何将元素添加到列表中?我尝试了类似[x]:y的东西,但是我得到的是每个元素作为列表并连接在一起,这不是结果。



我现在拥有的是

  foldr(\ xy  - > if x> = 0 then [x]:y else y)[[]] ] 

这是错误的

非常感谢 代替。不过,我想提出0在数学中不被视为正数的观点。至于目前为止还没有其他答案提及过, Num typeclass的任何内容都必须实现 signum ,它将返回

  import Data.List(groupBy)
import Data.Function(on ) - 可以避开lambda

signGroup ::(Num a)=> [a] - > [[a]]
signGroup = groupBy((==)`on signum)

用法示例:

 > signGroup [1,2,3,0,0,-1,-2,1,2,0,3,4,-1] 
[[1,2,3],[0,0], [-1,-2],[1,2],[0],[3,4],[ - 1]]


Given a list of sequence of negative and positive numbers, how can I partition them into sequences of negative and positive numbers using foldr?

For example [1,2,3,-1,-2,-3,1,2,3] i will get [[1,2,3],[-1,-2,-3],[1,2,3]]

A few doubts

How do I know that the previous partition that I have already compared if of the same sign as the one I am comparing current?

How do I add the element to the list? I tried something like [x]:y but what I get was each element as a list and concatenated together, which is not the result.

What I have currently is this

foldr (\ x y -> if  x >= 0  then [x]:y else y ) [[]] 

which is wrong

Many thanks for the help in advance.

解决方案

I second the usage of groupBy instead. However I'd like to raise the point that 0 is not considered a positive number in mathematics. And as no other answers have so far mentioned, anything that is of the Num typeclass must implement signum, which will return the sign of the number given to it.

import Data.List     (groupBy)
import Data.Function (on) -- Can evade a lambda

signGroup :: (Num a) => [a] -> [[a]]
signGroup = groupBy ((==) `on` signum)

Example usage:

> signGroup [1,2,3,0,0,-1,-2,1,2,0,3,4,-1]
[[1,2,3],[0,0],[-1,-2],[1,2],[0],[3,4],[-1]]

这篇关于haskell foldr与列表操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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