Skip to content

Instantly share code, notes, and snippets.

@MonoidMusician
Created September 8, 2017 18:47
Show Gist options
  • Save MonoidMusician/f4606fba71def8f7f99ae05f20a723dc to your computer and use it in GitHub Desktop.
Save MonoidMusician/f4606fba71def8f7f99ae05f20a723dc to your computer and use it in GitHub Desktop.
Alternative find
module Main where
import Prelude
import Control.Monad.Eff.Console (logShow)
import TryPureScript (render, withConsole)
import Control.Alternative (class Alternative)
import Control.Plus (class Plus)
import Control.Alt (class Alt)
import Data.Foldable (class Foldable, foldMap)
import Data.Newtype (class Newtype, unwrap)
import Data.Monoid.Alternate (Alternate(..))
import Data.Monoid (mempty)
import Data.Maybe (Maybe(..))
-- Custom newtype since `Last` does not include a `Plus` instance ...
newtype Last a = Last (Maybe a)
derive instance newtypeLast :: Newtype (Last a) _
instance showLast :: Show a => Show (Last a) where
show (Last a) = "(Last " <> show a <> ")"
derive newtype instance functorLast :: Functor Last
derive newtype instance applyLast :: Apply Last
derive newtype instance applicativeLast :: Applicative Last
instance altLast :: Alt Last where
alt a (Last Nothing) = a
alt _ b = b
instance plusLast :: Plus Last where
empty = Last Nothing
instance alternativeLast :: Alternative Last
find :: ∀ a c m. Foldable c ⇒ Alternative m ⇒ (a → Boolean) → c a → m a
find f = unwrap <<< foldMap \a -> if f a then Alternate (pure a) else mempty
main = render =<< withConsole do
logShow (find (_ > 4) [3, 4, 5, 6, 7, 2, 8] :: Array Int)
logShow (find (_ > 4) [3, 4, 5, 6, 7, 2, 8] :: Maybe Int)
logShow (find (_ > 4) [3, 4, 5, 6, 7, 2, 8] :: Last Int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment