当Haskell中的功能不正确时,我只能切片列表?

发布于 2025-02-07 00:07:19 字数 435 浏览 2 评论 0原文

当功能不正确时,我想切片列表,但是我不知道在其他情况下我必须回馈什么。你有什么想法吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如果没有你 2025-02-14 00:07:19

您可以使用 past (a - > bool) - > [a] - > ([a],[a]) break ::(a - > bool) - > [a] - > ([a],[a]) 获得列表所能/不满足给定谓词的最长前缀。因此,您可以使用它来制作两个函数slicebyslicebynot相互调用:

sliceBy :: (a -> Bool) -> [a] -> [[a]]
sliceBy _ [] = []
sliceBy f xs = … : …
    where (xp, xnp) = span f xs

sliceByNot :: (a -> Bool) -> [a] -> [[a]]
sliceByNot _ [] = []
sliceByNot f xs = … : …
    where (xnp, xp) = break f xs

您需要填写 parts。因此,这两个功能应该互相呼叫。

You can make use of span :: (a -> Bool) -> [a] -> ([a], [a]) and break :: (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 functions sliceBy and sliceByNot that call each other:

sliceBy :: (a -> Bool) -> [a] -> [[a]]
sliceBy _ [] = []
sliceBy f xs = … : …
    where (xp, xnp) = span f xs

sliceByNot :: (a -> Bool) -> [a] -> [[a]]
sliceByNot _ [] = []
sliceByNot f xs = … : …
    where (xnp, xp) = break f xs

Where you need to fill in the parts. The two functions thus should call each other.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文