1
\$\begingroup\$

I was wondering why replace is not in base. I thought, it's because it must be easy to implement with standard combinators. Although I do not like prefix syntax of Applicative I wrote it this way:

replace a b = map (bool <$> id <*> (const b) <*> (== a))

And was slightly surprised after seeing replace in Data.List.Utils:

replace old new l = join new . split old $ l

Are there non-opinion based reasons to prefer one than the other in public projects?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 2, 2015 at 17:01
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

Your code is not a replacement for replace (pun intended). Its type signature is wrong. Your code has type Eq b => b -> b -> [b] -> [b], but replace should have type Eq a => [a] -> [a] -> [a] -> [a].

<$> and <*> are infix, not prefix.

I'd prefer this to your implementation:

replace' :: Eq b => b -> b -> [b] -> [b]
replace' a b = map (\x -> if (a == x) then b else x)

It does the exact same thing in the exact same way, but is simpler and more readable (even a novice Haskell programmer who has never heard of bool or <$> or <*> can read it). Even more important: it has a type signature.

If you'd decided to cut-and-paste the type signature of the function you wanted to replicate before starting, you would have found out that your version doesn't work as a replacement at compile time -- and if you'd looked at and thought about the type signature, you probably would have wondered why the extra []s were there, and figured it out even earlier.

200_success
145k22 gold badges190 silver badges478 bronze badges
answered Apr 2, 2015 at 23:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.