What I want is to "compose" functions taking some argument and
returning an Alt
value, like a -> m b
where Alt b
. The
resulting value should be a function from a -> m b
. The
implementation below does that, but I was wondering if there's
a better way? I'm thinking that maybe I could create a newtype
wrapper around these functions, and an Alt
instance for that
type, but I haven't gotten that to work, and I'm not sure it's
a good approach.
composeAlt :: forall m a b. Alt m => (a -> m b) -> (a -> m b) -> a -> m b
composeAlt f g x = f x <|> g x
infix 4 composeAlt as <||>
To expand a bit on why I need this, I have functions that represent
HTTP server routes, and they return MaybeT (Aff e)
values,
representing if the route matched the request or not. I need to compose
these functions in such a way that the chain of functions will be tried
in sequence until one returns a Just
value. If all fail to match then
I can fallback to a 404 response.
myRoutes = home <||> projects <||> contact <||> whatever
I think you can just use the
Alt
instance arising through your use ofMaybeT
. I knew to look for that instance because I had just read this blogpost describing exactly what you are looking for: http://www.parsonsmatt.org/2016/11/18/clean_alternatives_with_maybet.htmlhttps://github.com/purescript/purescript-transformers/blob/ab7ccac64cf709af722961f246a6e426dc5e326d/src/Control/Monad/Maybe/Trans.purs#L64-L69