5

我有以下函数,它接受一个列表并返回在给定元素 n 处拆分的两个子列表。但是,我只需要将它分成两半,奇数长度的列表具有更大的第一个子列表

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) 这样的内容,以免中断递归?

4

2 回答 2

10

在实际程序中,您可能应该使用

splitlist :: [a] -> ([a], [a])
splitlist xs = splitAt ((length xs + 1) `div` 2) xs

(即类似于dreamcrash的答案。)

但是,如果出于学习目的,您正在寻找一个明确的递归解决方案,请研究以下内容:

splitlist :: [a] -> ([a], [a])
splitlist xs = f xs xs where
    f (y : ys) (_ : _ : zs) =
        let (as, bs) = f ys zs
        in (y : as, bs)
    f (y : ys) (_ : []) = (y : [], ys)
    f ys [] = ([], ys)
于 2012-12-09T12:38:34.880 回答
8

您可以使用 take 和 drop 来做到这一点:

splitlist :: [a] -> ([a],[a])
splitlist [] = ([],[])
splitlist l  = let half = (length(l) +1)`div` 2
               in (take half l, drop half l)

或者您可以利用函数 splitAt:

splitlist list = splitAt ((length (list) + 1) `div` 2) list
于 2012-12-09T05:00:04.477 回答