Skip to content

Instantly share code, notes, and snippets.

@naohaq
Created July 7, 2013 03:39
Show Gist options
  • Save naohaq/5942180 to your computer and use it in GitHub Desktop.
Save naohaq/5942180 to your computer and use it in GitHub Desktop.
module Sumlen where
sumList :: (Num a) => [a] -> a
sumList = foldr (+) 0
lenList :: (Num b) => [a] -> b
lenList = foldr (\_ y->y+1) 0
sumlenList :: (Num a, Num b) => [a] -> (a,b)
sumlenList = foldr (\x (y,z)->(x+y,z+1)) (0,0)
averageList :: (Fractional a) => [a] -> a
averageList xs = y / z
where (y,z) = sumlenList xs
data Tree a = Leaf a | Fork (Tree a) (Tree a) deriving Show
foldTree :: (a -> b) -> (b -> b -> b) -> Tree a -> b
foldTree f _ (Leaf x) = f x
foldTree f g (Fork xt yt) = g (foldTree f g xt) (foldTree f g yt)
sumTree :: (Num a) => Tree a -> a
sumTree = foldTree id (+)
lenTree :: (Num b) => Tree a -> b
lenTree = foldTree (\_->1) (+)
sumlenTree :: (Num a, Num b) => Tree a -> (a,b)
sumlenTree = foldTree (\x -> (x,1)) (\(x0,y0) (x1,y1)->(x0+x1,y0+y1))
averageTree :: (Fractional a) => Tree a -> a
averageTree xs = y / z
where (y,z) = sumlenTree xs
xt :: (Num a) => Tree a
xt = Fork (Fork (Leaf 5) (Fork (Leaf 1) (Leaf 2))) (Fork (Leaf 4) (Leaf 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment