Welcome to the Functional Programming Zulip Chat Archive. You can join the chat here.
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:
f
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)
a
or better the following:
compute' :: Alternative f => (a -> f b) -> (a -> b) -> (a -> b) compute' f g = undefined
I don't think the Alternative one is possible without some Eq constraints
Alternative
Eq
Ok, you can add Eq or any constraints you think are needed (just so that Maybe has instances of them)
Maybe
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
Wow thanks, Georgi! I will need some time to digest it! :)
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!
liftA2
(r ->)
Applicative
> compute = flip (liftA2 fromMaybe) > :t compute compute :: Applicative f => f (Maybe c) -> f c -> f c
compute f g = fromMaybe <$> g <*> f
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:
f
returns Just, return that valueg
; 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:
I don't think the
Alternative
one is possible without someEq
constraintsOk, you can add
Eq
or any constraints you think are needed (just so thatMaybe
has instances of them)Wow thanks, Georgi! I will need some time to digest it! :)
this
liftA2
is using the(r ->)
instance forApplicative
, but if you don't actually restrict it, it turns out that it's good for anyApplicative
!