gpt4 book ai didi

haskell - 在haskell中用foldr分割

转载 作者:行者123 更新时间:2023-12-02 04:18:21 25 4
gpt4 key购买 nike

我需要使用foldr编写一个函数split

split :: Eq a ⇒ a → [a] → [[ a ]]

示例:

split '/' ”hello/my/friends” ----> [”hello”,”my”,”friends”]

这是我尝试过的:

split :: Eq a ⇒ a → [a] → [[ a ]]
split str delim = let (start, end) = break (== delim) str
in start : if null end then [] else groupBy (tail end) delim

最佳答案

这样的事情应该有效:

foldr (\c (x:xs) ->
if c == '/'
then "":x:xs
else (c:x):xs
) [""] "hello/my/friends"

广义:

split on = foldr (\c (x:xs) ->
if c == on
then []:x:xs
else (c:x):xs
) [[]]

关于haskell - 在haskell中用foldr分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com