本文介绍了简单的haskell splitlist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下面的函数,它需要一个列表并返回在给定元素n处分割的两个子列表。然而,我只需要将它分成两半,奇数长度的列表具有较大的第一个子列表。
I have the following function which takes a list and returns two sublists split at a given element n. However, I only need to split it in half, with odd length lists having a larger first sublist
splitlist :: [a] -> Int -> ([a],[a])
splitlist [] = ([],[])
splitlist l@(x : xs) n | n > 0 = (x : ys, zs)
| otherwise = (l, [])
where (ys,zs) = splitlist xs (n - 1)
我知道我需要将签名更改为[a] - >([a],[a]),但是在代码中我应该放入类似length(xs)的东西,以便不会中断递归?谢谢。
I know I need to change the signature to [a] -> ([a],[a]), but where in the code should I put something like length(xs) so that I don't break recursion? Thank you.
推荐答案
您可以使用take and drop:
You can do it using take and drop:
splitlist :: [a] -> ([a],[a])
splitlist [] = ([],[])
splitlist l = let half = (length(l) +1)`div` 2
in (take half l, drop half l)
或者您可以利用splitAt函数:
or you can take advantage of the function splitAt:
splitlist list = splitAt ((length (list) + 1) `div` 2) list
这篇关于简单的haskell splitlist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!