Wednesday, 15 April 2015

haskell - Transform a -> a -> Maybe a to take any combination of a's and Maybe a's -



haskell - Transform a -> a -> Maybe a to take any combination of a's and Maybe a's -

i have function f of type integral => -> -> maybe a. means that

f 1 2

is valid code, natural compositions like

f (f 3 4) 5 f 6 (f 7 8) f (f 9 10) (f 11 12)

are not valid.

there ways create work. example,

f 6 =<< f 7 8

is nicest way know case 2. case 3,

join $ f <$> f 9 10 <*> f 11 12

is best can think of, join sticks out sore thumb. don't have thought case 1. besides that, bothers me syntax in came not "consistent" - i'm accomplishing same thing, syntax dissimilar.

is there standard/idiomatic construction allows me convert f work maybe -> -> maybe a, a -> maybe -> maybe a, , maybe -> maybe -> maybe a, nice , consistent syntax?

original solution

let's create utility function first case:

lift :: (a -> b -> maybe c) -> maybe -> b -> maybe c lift _ nil _ = nil lift f (just a) b = f b

case 1:

lift f (f 3 4) 5

case 2:

f 6 =<< f 7 8

case 3:

lift f (f 9 10) =<< f 11 12

although looks more consistent, yet in humble sentiment still looks ugly. perhaps else provide improve solution.

recommended solution

edit: after thinking solution realized can generalized:

(<&>) :: (applicative m, monad m) => m (a -> m b) -> m -> m b f <&> = bring together $ f <*> infixl 4 <&>

case 1:

f <$> f 3 4 <&> pure 5

case 2:

f <$> pure 6 <&> f 7 8

case 3:

f <$> f 9 10 <&> f 11 12

this works functions of arbitrary arity:

f <$> <&> b -- f :: -> -> maybe f <$> <*> b <&> c -- f :: -> -> -> maybe f <$> <*> b <*> c <&> d -- f :: -> -> -> -> maybe

and on....

alternate solution

edit: agree @n.m. best solution alter type signature of function maybe -> maybe -> maybe a , utilize just wherever necessary.

case 1:

f (f (just 3) (just 4)) (just 5)

case 2:

f (just 6) (f (just 7) (just 8))

case 3:

f (f (just 9) (just 10)) (f (just 11) (just 12))

the simplest solutions best.

edit: actually, in retrospect previous solution much simpler.

haskell

No comments:

Post a Comment