haskell foldr与列表操作 [英] haskell foldr manipulation with lists
问题描述
有些怀疑
我如何知道以前的分区,如果是相同的符号作为我比较当前的?
如何将元素添加到列表中?我尝试了类似[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屋!