Skip to content

Instantly share code, notes, and snippets.

@vertexcite
Created October 22, 2015 10:58
Show Gist options
  • Save vertexcite/098ee119e795c0343f7b to your computer and use it in GitHub Desktop.
Save vertexcite/098ee119e795c0343f7b to your computer and use it in GitHub Desktop.
Simpler `length`, `sum`, `product` for GHC 7.10 for beginners.
-- Something like this when teaching using GHC
-- so that beginners don't get confused by FTP versions
-- of length, sum, product, etc.
-- Usage: in ghci, `:l FtpFree.hs`
module FtpFree (length, sum, product) where
import Prelude hiding (length, sum, product)
length :: [a] -> Int
length = foldr (const (+1)) 0
-- length [] = 0
-- length (_:xs) = length xs + 1
sum :: Num a => [a] -> a
sum = foldr (+) 0
product :: Num a => [a] -> a
product = foldr (*) 1
{-
Deriving definition for length:
Start with:
length xs = foldr (\_ x -> x + 1) 0 xs
Eta reduce:
length = foldr (\_ x -> x + 1) 0
Use prefix (+):
length = foldr (\_ x-> (+) 1 x) 0
Eta reduce the lambda:
length = foldr (\_ -> (+) 1 ) 0
Use operator section:
length = foldr (\_ -> (+1) ) 0
This lambda is just const:
length = foldr (const (+1)) 0
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment