Skip to content

Instantly share code, notes, and snippets.

@vvv
Forked from mssawant/ordeq.hs
Created September 7, 2017 10:54
Show Gist options
  • Save vvv/bce2d363d464791a34900545f711cdc5 to your computer and use it in GitHub Desktop.
Save vvv/bce2d363d464791a34900545f711cdc5 to your computer and use it in GitHub Desktop.
import Data.Foldable (foldl')
import Debug.Trace (trace)
prnEqual :: (Eq a) => a -> a -> IO ()
prnEqual a b = if a == b then print "True" else print "False"
-- Note the absence of parentheses around `Eq a` and having exactly one `print`.
prnEqual' :: Eq a => a -> a -> IO ()
prnEqual' a b = print $ if a == b then "True" else "False"
prnGt :: (Ord a, Show a, Num a) => a -> a -> IO ()
prnGt _ b | b < 0 = error "Invalid input" -- XXX Note the use of `_`.
prnGt a b = if a > b then print a else print b
-- `Num a` constraint is not needed.
-- I am cheating here by allowing negative 2nd argument for the sake of brevity.
prnGt' :: (Ord a, Show a) => a -> a -> IO ()
prnGt' x = print . max x
reverseList :: [a] -> [a]
reverseList [] = error "List is empty"
reverseList l = foldl (\acc x -> x : acc) [] l -- Understand this can be done using
-- flip, but wanted to experiment with
-- fold.
-- Also want to print the input list here,
-- need suggestion.
-- 1. `foldl` is never used, AFAIK. Use `foldr` (can be applied to
-- infinite lists) or `foldl'` (strict).
-- 2. You don't need `l` argument;
-- see [https://wiki.haskell.org/Partial_application].
-- 3. IMO, reverting an empty list should return an empty list.
reverseList' :: [a] -> [a]
reverseList' = foldl' (flip (:)) [] -- XXX You can still use `flip`. :)
reverseTraced :: Show a => [a] -> [a]
reverseTraced = foldl' f []
where
-- See https://wiki.haskell.org/Debugging#Printf_and_friends
-- This idiom was heavily used during HALON-727 debugging.
f acc x | trace ("acc=" ++ show acc ++ " x=" ++ show x) False = undefined
f acc x = x:acc
mainOld :: IO ()
mainOld = do
prnEqual 1 1
prnGt 2 1
let l = reverseList [1,2,3,4]
print l
-- 1. 8 spaces is too wide an indentation for Haskell code.
-- I'd love if we used 4 spaces
-- (see [https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md#indentation]),
-- but Halon code uses 2 spaces (default of Emacs' haskell-mode, AFAIU).
-- 2. `let l` is not necessary.
-- 3. Use [1..4] instead of [1, 2, 3, 4].
main :: IO ()
main = do
mainOld
putStrLn "----------"
prnEqual' 1 1
prnGt' 2 1
let l = [1..4]
print $ reverseList' l
print $ reverseTraced l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment