当Haskell中的功能不正确时,我只能切片列表?
当功能不正确时,我想切片列表,但是我不知道在其他情况下我必须回馈什么。你有什么想法吗?
Example :
sliceBy odd [1..5] == [[1],[2],[3],[4],[5]]
sliceBy odd [1,3,2,4,5,7,4,6] == [[1,3],[2,4],[5,7],[4,6]]
sliceBy even [1,3,2,4,5,7,4,6] == [[],[1,3],[2,4],[5,7],[4,6]]
sliceBy :: (a -> Bool) -> [a] -> [[a]]
sliceBy _ [] = []
sliceBy _ [x] = [[x]]
sliceBy f (x:xs)
| f x = [x] : sliceBy f xs
| otherwise = ??
I would like to slice my list when the function is not true, but I do not have an idea what I have to give back in the otherwise case. Do you have any idea ?
Example :
sliceBy odd [1..5] == [[1],[2],[3],[4],[5]]
sliceBy odd [1,3,2,4,5,7,4,6] == [[1,3],[2,4],[5,7],[4,6]]
sliceBy even [1,3,2,4,5,7,4,6] == [[],[1,3],[2,4],[5,7],[4,6]]
sliceBy :: (a -> Bool) -> [a] -> [[a]]
sliceBy _ [] = []
sliceBy _ [x] = [[x]]
sliceBy f (x:xs)
| f x = [x] : sliceBy f xs
| otherwise = ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
past (a - > bool) - > [a] - > ([a],[a])
和break ::(a - > bool) - > [a] - > ([a],[a])
获得列表所能/不满足给定谓词的最长前缀。因此,您可以使用它来制作两个函数sliceby
和slicebynot
相互调用:您需要填写
…
parts。因此,这两个功能应该互相呼叫。You can make use of
span :: (a -> Bool) -> [a] -> ([a], [a])
andbreak :: (a -> Bool) -> [a] -> ([a], [a])
to get the longest prefixes where the list does/does not satisfy a given predicate. You thus can use this to make two functionssliceBy
andsliceByNot
that call each other:Where you need to fill in the
…
parts. The two functions thus should call each other.