Skip to content

Instantly share code, notes, and snippets.

@ttuegel
Created January 4, 2018 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttuegel/81aa94a56af4473e4d7747512fc2a3cf to your computer and use it in GitHub Desktop.
Save ttuegel/81aa94a56af4473e4d7747512fc2a3cf to your computer and use it in GitHub Desktop.
What does lazy pattern matching do?
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ViewPatterns #-}
module LazyPattern where
import Debug.Trace (trace)
data Foo a = Foo a
deriving (Show)
data Bar a = Bar a
deriving (Show)
-- | Lazy pattern matching
-- The argument is not evaluated until 'a' is forced.
--
-- >>> lazy (Foo ())
-- Bar right a
-- Foo
-- left a
-- ()
lazy ~(trace "Foo" -> Foo (trace "left a" -> a)) =
Bar (trace "right a" a)
-- | Ordinary pattern matching
-- The argument is evaluated to weak head normal form before 'Bar' is applied.
--
-- >>> weak (Foo ())
-- Foo
-- Bar right a
-- left a
-- ()
weak (trace "Foo" -> Foo (trace "left a" -> a)) =
Bar (trace "right a" a)
-- | Strict pattern matching
-- 'a' is evaluated to weak head normal form before 'Bar' is applied.
--
-- >>> strict (Foo ())
-- Foo
-- left a
-- Bar right a
-- ()
strict (trace "Foo" -> Foo (trace "left a" -> !a)) =
Bar (trace "right a" a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment