Skip to content

Instantly share code, notes, and snippets.

@olligobber
Last active February 10, 2021 09:15
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 olligobber/a2b48af361aa20d1751846924bb268c2 to your computer and use it in GitHub Desktop.
Save olligobber/a2b48af361aa20d1751846924bb268c2 to your computer and use it in GitHub Desktop.
-- Normal if statement, requires brackets or associative operators for nesting.
if' :: Bool -> a -> a -> a
if' b x y = if b then x else y
{-
Magic if statement, no brackets needed.
`magicIf` and `magicElseIf` pass on a function, that is either `id` or
`const x` saying what to do when a True or Else case is reached, to the next
`magicElseIf` or `magicElse`.
-}
magicIf :: Bool -> a -> ((a -> a) -> t) -> t
magicIf b x f = f (if' b x)
magicElseIf :: (a -> a) -> Bool -> a -> ((a -> a) -> t) -> t
magicElseIf c b x f = f (c . if' b x)
magicElse :: (a -> a) -> a -> a
magicElse = id
{-
Magic list building, no brackets or associative operators needed.
`magicList` and `magicElem` pass on the list so far to the next `magicElem` or
`magicEnd`.
-}
magicList :: ([a] -> t) -> t
magicList f = f []
magicElem :: a -> [a] -> ([a] -> t) -> t
magicElem l i f = f (i ++ [l])
magicEnd :: [a] -> [a]
magicEnd = id
{-
Example usage, where you can comment or uncomment cases and elements to see
its flexibility.
-}
main :: IO ()
main = do
putStrLn "What colour do you like?"
colour <- getLine
putStrLn $
magicIf (colour == "red")
"Yay, I like that colour"
magicElseIf (colour == "purple")
"Whoa, fancy"
-- magicElseIf (colour == "black")
-- "That's not a colour!"
magicElse
"Nice"
putStrLn . unwords $
magicList
(magicElem "Thanks")
(magicElem "for")
(magicElem "using")
(magicElem "my")
-- (magicElem "very")
(magicElem "magic")
(magicElem "functions.")
magicEnd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment