Give a solution to a problem - Haskell

Welcome to the Functional Programming Zulip Chat Archive. You can join the chat here.

Martins

What could be a canonical solution for the following problem? I can't seem to find proper combinators.

Write a function, which returns another function, that:

  1. If the result of calling f returns Just, return that value
  2. Otherwise return result of g
compute :: (a -> Maybe b) -> (a -> b) -> (a -> b)
compute f g = undefined

; I don't like this solution (\a -> fromMaybe (g a) $ f a)
; I would like not to have a in function body at all! (point free)

or better the following:

compute' :: Alternative f => (a -> f b) -> (a -> b) -> (a -> b)
compute' f g = undefined
Georgi Lyubenov // googleson78

I don't think the Alternative one is possible without some Eq constraints

Martins

Ok, you can add Eq or any constraints you think are needed (just so that Maybe has instances of them)

Georgi Lyubenov // googleson78
compute f g x = fromMaybe (g x) $ f x
compute f g x = fromMaybe (g x) (f x)
compute f g x = liftA2 fromMaybe g f x
compute f g = liftA2 fromMaybe g f
compute f g = flip (liftA2 fromMaybe) f g
compute = flip (liftA2 fromMaybe)
compute = flip $ liftA2 fromMaybe
Martins

Wow thanks, Georgi! I will need some time to digest it! :)

Georgi Lyubenov // googleson78

this liftA2 is using the (r ->) instance for Applicative, but if you don't actually restrict it, it turns out that it's good for any Applicative!

Georgi Lyubenov // googleson78
> compute = flip (liftA2 fromMaybe)
> :t compute
compute :: Applicative f => f (Maybe c) -> f c -> f c
rednaZ
compute f g = fromMaybe <$> g <*> f