tuples - Graph of a partial function in Haskell: a -> Maybe b -> [a] -> [(a, b)] -
given partial function f , list of arguments xs, i'm looking list of pairs (x, f(x)) f defined. seems natural thing do, far i've failed express elegantly. wonder if there's in maybe/monad/applicative/... area can help? following works, seems little explicit.
import data.maybe (mapmaybe) graph :: (a -> b) -> [a] -> [(a, b)] graph f = map (\x -> (x, f x)) liftmaybe :: (a, maybe b) -> maybe (a, b) liftmaybe (x, y) = (x, y) liftmaybe (_, nothing) = nothing partialgraph :: (a -> maybe b) -> [a] -> [(a, b)] partialgraph f = mapmaybe liftmaybe . graph f does liftmaybe exist name? i've found following reformulations of of these:
import control.monad (ap) graph' :: (a -> b) -> [a] -> [(a, b)] graph' = map . ap (,) liftmaybe' :: (a, maybe b) -> maybe (a, b) liftmaybe' (a, mb) = b <- mb return (a, b) liftmaybe'' :: (a, maybe b) -> maybe (a, b) liftmaybe'' (a, mb) = fmap ((,) a) mb liftmaybe''' :: (a, maybe b) -> maybe (a, b) liftmaybe''' = uncurry (fmap . (,))
the simplest definition of liftmaybe be
import data.traversable (sequencea) liftmaybe :: (a, maybe b) -> maybe (a, b) liftmaybe = sequencea the documentation sequencea can found here http://hackage.haskell.org/package/base/docs/data-traversable.html.
the general type signature sequencea :: (traversable t, applicative f) => t (f a) -> f (t a), in case t (,) c , f maybe.
also, partialgraph expressed traverse :: (traversable t, applicative f) => (a -> f b) -> t -> f (t b) (which data.traversable):
partialgraph :: (a -> maybe b) -> [a] -> [(a, b)] partialgraph f = mapmaybe $ \x -> traverse f (x, x) or, if prefer little more pointlessness:
partialgraph f = mapmaybe (traverse f . join (,)) edit: when wrote answer, didn't realize required traversable , foldable instances aren't defined in ghc 7.6.3 standard library (they in ghc 7.8 though). here are, courtesy of @robx:
instance foldable ((,) a) foldr f y (u, x) = f x y instance traversable ((,) a) traverse f (u, x) = (,) u <$> f x
Comments
Post a Comment