【问题标题】:How to split a list into two in Haskell? [duplicate]如何在 Haskell 中将列表一分为二? [复制]
【发布时间】:2013-09-29 04:48:28
【问题描述】:

我正在尝试将一个列表分成两部分,以便当输入为

[1,2,3,5,6]

输出是

[1,2,3][5,6] 

但我似乎无法弄清楚。

我能做的最好的就是[1,3,6][2,5]

【问题讨论】:

  • 你能把你已经写好的代码贴出来吗?如果不知道自己在尝试什么,就不可能为您指明正确的方向。另外,你能再定义一下你的函数吗?如果输入不同长度的列表怎么办?拆分列表的条件是什么?

标签: haskell split tuples


【解决方案1】:

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

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]

输出

[[1,2,3],[5,6]]
[[1,2,3],[4,5,6]]

编辑:

设法使用内置函数并想出了这个

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]

输出

[[1,2,3],[5,6]]
[[1,2,3],[4,5,6]]

编辑 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]

输出

([1,2,3],[5,6])
([1,2,3],[4,5,6])

编辑2

正如 Bogdon 在 cmets 部分所建议的,这可以大大简化为

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]

输出

([1,2,3],[5,6])
([1,2,3],[4,5,6])

【讨论】:

  • 那为什么不使用splitAt呢? splitHalf l = splitAt ((length l + 1) `div` 2) l
  • 我在第二次编辑中使用了它,但不如你的简洁。谢谢:)
  • @Bogdan 用这个解决方案更新了我的答案。
猜你喜欢
  • 2013-02-17
  • 2023-03-28
  • 2015-12-09
  • 1970-01-01
  • 2017-09-20
  • 2017-11-18
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
相关资源
最近更新 更多