Search code examples
haskellpointfree

What is the best way to do "replace-if"?


I'm thinking of a function that can replace the value x with z when x is y, and do nothing otherwise, that is:

\x -> if x == y then z else x

It's only used once in my program and it's in the middle of a function chain so I don't want to define it as a named function and I think the lambda expression looks unnecessarily verbose. Instead, I'm trying to compose it from other functions. However, so far I have only come up with this cryptic (and cring-y) one:

(ap . flip . bool id $ const z) (== y)

Are there better point-free forms for such a simple function?


Solution

  • I don't know of anything very readable. Shortest I can get is

    bool z <*> (/= y)
    

    Further silly ways:

    execState (gets (==y) >>= flip when (put z))
    
    fromMaybe <*> flip lookup [(y, z)]