作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将一个列表分成两部分,以便当输入为
[1,2,3,5,6]
输出是
[1,2,3][5,6]
但我似乎无法弄清楚。
我能做的最好的就是[1,3,6][2,5]
。
最佳答案
我是初学者。所以,如果这是错误的或次优的,请纠正我。
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
正如博格登在评论部分所建议的那样,这可以大大简化为
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])
关于haskell - 如何在 Haskell 中将列表一分为二?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19074520/
我是一名优秀的程序员,十分优秀!