Skip to content

Instantly share code, notes, and snippets.

@missingfaktor
Created October 6, 2011 09:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save missingfaktor/1266912 to your computer and use it in GitHub Desktop.
Save missingfaktor/1266912 to your computer and use it in GitHub Desktop.
-- A simple definition without using any fancy functions.
haskell>let ifMaybe pred value = if pred value then Just value else Nothing
haskell>:t ifMaybe
ifMaybe :: (a -> Bool) -> a -> Maybe a
haskell>ifMaybe (const True) 2
Just 2
haskell>ifMaybe (const False) 2
Nothing
-- Using functions from standard library.
haskell>let ifMaybe pred value = mfilter pred $ Just value
haskell>:t ifMaybe
ifMaybe :: (a -> Bool) -> a -> Maybe a
haskell>ifMaybe (const True) 2
Just 2
haskell>ifMaybe (const False) 2
Nothing
-- A point-free version that uses section of (.).
haskell>let ifMaybe = (. Just) . mfilter
haskell>:t ifMaybe
ifMaybe :: (a -> Bool) -> a -> Maybe a
haskell>ifMaybe (const True) 2
Just 2
haskell>ifMaybe (const False) 2
Nothing
-- Same thing written with (<.|) combinator.
haskell>let ifMaybe = mfilter <.| Just
haskell>:t ifMaybe
ifMaybe :: (a -> Bool) -> a -> Maybe a
haskell>ifMaybe (const True) 2
Just 2
haskell>ifMaybe (const False) 2
Nothing
haskell>
@missingfaktor
Copy link
Author

With some help of @djinn and @pl commands of lambdabot...

Prelude Control.Arrow Control.Applicative> let regular = (. (,)) . (.)
Prelude Control.Arrow Control.Applicative> :t regular
regular :: ((a, b) -> c) -> a -> b -> c
Prelude Control.Arrow Control.Applicative> let f |.> g = regular $ f . uncurry g
Prelude Control.Arrow Control.Applicative> :t (|.>)
(|.>) :: (b1 -> c) -> (a -> b -> b1) -> a -> b -> c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment