【发布时间】:2018-03-19 07:37:45
【问题描述】:
如果我有一个列表,比如说[1,2,3,4],我如何创建一个包含两个列表的元组,以便第一个列表包含奇数元素,第二个列表包含偶数元素。如何使用尾递归做到这一点?
例如:
Input : [1,2,3,4]
Output : ([1,3],[2,4]) with tail recursion and not ranges. [|x<-...]
到目前为止,我已经尝试过类似的方法:
sumt::[Int]->([Int],[Int])
sumt []=([],[])
sumt (x:xs)
| x `mod` 2==0 = x: (fst $ tupl xs)
| otherwise = x: (snd $ tupl xs) where
tupl []=([],[])
tupl (y:ys)=y:(tupl ys) //how can I put the condition here ? I need it
//to be aware of both guard cases at each iteration
我基本上需要两个由每个保护案例形成的本地列表,最后它们被放置在一个元组中。
【问题讨论】:
-
你确定你希望它是尾递归的吗?为什么?此外,您尝试过的代码不是尾递归的。
-
// Comment不是 Haskell 评论。使用-- Comment。 -
我正在尝试使用守卫和尾递归解决问题。有什么办法可以生成空元组和空列表并使用递归填充它们
-
even和odd是 Prelude 中的函数。even 4将返回True。
标签: haskell tuples list-comprehension