如何在haskell中将列表拆分为两个?

use*_*677 1 haskell split tuples

我正在尝试将列表拆分为两个,这样当输入[1,3,6][2,5]输出时[1,3,6][2,5],我似乎无法弄明白.我能做的最好的是[1,3,6][2,5].

the*_*eye 6

我是初学者.所以,如果这是错误的或次优的,请纠正我.

internalSplit :: [a] -> Int -> [a] -> [[a]]
split :: [a] -> [[a]]

internalSplit (first:rest) count firstPart
    | count == 0 = [firstPart, (first:rest)]
    | otherwise  = internalSplit rest (count - 1) (firstPart ++ [first])

split myList =
    let listLength = length myList
    in
        if listLength `mod` 2 == 0 then
            internalSplit myList (listLength `div` 2) []
        else
            internalSplit myList ((listLength `div` 2) + 1) []

main = do
        print $ split [1, 2, 3, 5, 6]
        print $ split [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

产量

[[1,2,3],[5,6]]
[[1,2,3],[4,5,6]]
Run Code Online (Sandbox Code Playgroud)

编辑:

管理使用内置函数并想出了这个

internalSplit :: [a] -> Int -> [[a]]
split :: [a] -> [[a]]

internalSplit myList splitLength = [(take splitLength myList), (drop splitLength myList)]

split myList =
    let listLength = length myList
    in
        if listLength `mod` 2 == 0 then
            internalSplit myList (listLength `div` 2)
        else
            internalSplit myList ((listLength `div` 2) + 1)

main = do
        print $ split [1, 2, 3, 5, 6]
        print $ split [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

产量

[[1,2,3],[5,6]]
[[1,2,3],[4,5,6]]
Run Code Online (Sandbox Code Playgroud)

编辑1:

internalSplit :: [a] -> Int -> ([a], [a])
split :: [a] -> ([a], [a])

internalSplit myList splitLength = splitAt splitLength myList

split myList =
    let listLength = length myList
    in
        if listLength `mod` 2 == 0 then
            internalSplit myList (listLength `div` 2)
        else
            internalSplit myList ((listLength `div` 2) + 1)

main = do
        print $ split [1, 2, 3, 5, 6]
        print $ split [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

产量

([1,2,3],[5,6])
([1,2,3],[4,5,6])
Run Code Online (Sandbox Code Playgroud)

EDIT2

正如Bogdon在评论部分所建议的那样,这可以大大简化

split :: [a] -> ([a], [a])
split myList = splitAt (((length myList) + 1) `div` 2) myList
main = do
        print $ split [1, 2, 3, 5, 6]
        print $ split [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

产量

([1,2,3],[5,6])
([1,2,3],[4,5,6])
Run Code Online (Sandbox Code Playgroud)

  • 为什么不使用[``splitAt``](http://hackage.haskell.org/package/base-4.6.0.1/docs/Prelude.html#v:splitAt)呢?``splitHalf l = splitAt((长度l + 1)`div` 2)l`` (5认同)