如何解决将给定值上的列表分解为子列表列表
let obj={A:'a',B:'b'};
函数需要从列表中删除给定值并返回列表列表。这些子列表对每个元素进行分组,直到它遇到需要删除的值。发生这种情况时,将启动一个新的子列表。
multipleLists
我认为 input: multipleLists 'b' "abcabc"
expected output: ["a","ca","c"]
actual output: ["a","c","a","c"]
input: multipleLists 1 [0,1,2,3,4,4]
expected output: [[0],[2,4],[3,4]]
actual output: [[0],[2],[3],[4],[4]]
的情况有问题,但我有点卡住了。
这是我的代码:
otherwise
解决方法
multipleListsAllowEmpty value list =
let (beginning,end) = break (value ==) list
in beginning : case end of
[] -> []
(_:xs) -> multipleListsAllowEmpty value xs
multipleLists value = filter (not . null) . multipleListsAllowEmpty
在这里,我们从 break
导入 Data.List
。
我们可以更简洁地表达multipleListsAllowEmpty
maybeTail [] = Nothing
maybeTail (_:xs) = Just xs
multipleListsAllowEmpty value =
toList . unfoldr (fmap maybeTail . break (value ==))
我们从 unfoldr
导入 toList
和 Data.List.NonEmpty
。
这是您使用累加器的修改版本 - 除了 reverse
(您可以通过更改累加器的构建方式将其删除)之外,它不使用任何外部内容:
multipleLists :: Eq a => a -> [a] -> [[a]]
multipleLists value = go []
where
go [] [] = []
go [] (x:xs)
| x == value = go [] xs
| otherwise = go [x] xs
go acc [] = [reverse acc]
go acc (x:xs)
| x == value = reverse acc : go [] xs
| otherwise = go (x:acc) xs
你的例子(见我上面的评论):
> multipleLists 'b' "abcabc"
["a","ca","c"]
> multipleLists (1 :: Int) [0,1,2,3,4,4]
[[0],[2,4],[3,4]]
,
multipleLists 0 [0,0]
的预期值是什么?
是[]
还是[[]]
还是[[],[]]
?
这里有两种解决方案,它们以不同的方式处理这些情况,均基于右折叠。
splitList :: Eq a => a -> [a] -> [[a]]
splitList x = tail . foldr sx [[]] . (x:)
where
sx y ws@(zs:zss) | y == x = [] : ws
| otherwise = (y:zs) : zss
multipleLists :: Eq a => a -> [a] -> [[a]]
multipleLists x = filter (not . null) . foldr sx [[]] . (x:)
where
sx y ws@(zs:zss) | y == x = [] : ws
| otherwise = (y:zs) : zss
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。