Haskell - Does a replace function exist?

故事扮演 提交于 2019-12-04 09:54:34

replace exists in Data.List.Utils, part of MissingH package.

Actually, it's a really concise implementation:

replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace old new = join new . split old

First off, join is a bad name as that's already a standard function. Also, I have no idea why you define this function, in this way – it doesn't seem to do anything much useful.

But ok, you did try something. So let's now find a proper solution...

As is usually a good idea in Haskell, we want to break this up into sub-problems. What's first needed is to find the sub-strings you'd like to replace. This could look something like

locateSub :: (Eq a) =>
        [a]             -- ^ The sought sublist.
     -> [a]             -- ^ The source list.
     -> Maybe ([a],[a]) -- ^ Everything to the left and, if found, everything
                        -- to the right of the sought sublist. No need to return
                        -- the sublist itself in between since we already know it!

Using this function, replace is straight-forward:

replace oldSub newSub list
    = case locateSub oldSub list of
        Nothing -> list   -- Sublist not found: we're done already!
        Just (l, r) -> l ++ newSub ++ replace oldSub newSub r

replaceBasedIdx isn't much more difficult, you only need to recurse over a list of newSubs rather than passing it always as-is.

So what you need to do is implement locateSub. With isPrefixOf you're already on the right track. Actually it looks a lot like your _replace (BTW: it's custumary in Haskell to use the prime ' rather than underscores to name "local variants / helpers" of a function, so you'd rather call it replace'.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!