real world haskell: http://book.realworldhaskell.org/read/ chap 6 ghc, ghci, runghc help: :? info: :info (+) include/load file: :l reload: :r quit: :q prompt: :set prompt "blabla" load modules: :module + Data.Ratio import List( nub ) arithmetic functions: + - ^ div mod abs infix functions: operators 1 + 2 can be used prefix: (+) 1 2 prefix: mod 1 2 can be used infix: 1 `mod` 2 logic operators: True False && || == /= >= operator precedence ? temporary definition (in ghci): let e = exp 1 scope: bind variables let: let fn = expr ... in expr function: funcionName arg1 arg2 | guard1 = expr1 | guard2 = expr2 | otherwise = exprotherwise with cases: xor True False = True xor False False = False ... xor True x = see type: :t fname maxThreeOccurs n n p = (maxVal, eqCount) where maxVal = ... eqCount = ... use spaces tuples/records: pair, triple, 4-tuple, ... (String, Int, Int) addPair :: (Int, Int) -> Int addPair (x,y) = x + y nested patterns: shift :: ((Int, Int), Int) -> (Int, (Int, Int)) first: fst (x,y;) patterns: let (a:b:c:[]) = "xyz" in a let (a:_) = "xyz" in a grab and pattern match/as-pattern/as pattern: let abc@(a,b,c) = (10, 20, 30) in (abc,a,b,c) lists: [1, 2, 3] [] [1..10] [2,4..10] ["a", "b", "c"] same type concat: [1,2,3] ++ [4,5] prepend: 1 : [2,3] first element: head list drop, take characters: 'a' strings: "asd\n\t" ['a', 'b', 'c', '\n', '\t'] "" == [] 'a':"bc" "foo" ++ "bar" words string unwords see types of expr: :set +t special variables: result of last expr: it rational numbers: :m +Data.Ratio 11 % 9 comments: -- comment {- comment -} files: .hs common basic types: Char Bool Int Integer Double shorthands for types/type synonyms: type Complex = (Float,Float) map: map func list map (+1) [1..5] right bind: let double = (*) 2 doubleList = map double in doubleList [1,2,3] filter half_a_bool_func list evaluation: from outside in, left to right upcase: toUpper folding: foldr higher level: fapp f g x = f (g x) iter 0 f x = x iter n f x = f (iter (n-1) f x) composition: (.) higher order functions: replicate :: Int -> a -> [a] curry :: (f -> a -> b -> c) -> f -> (a, b) -> b zip :: [a] -> [b] -> [(a,b)] zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] infinite lists: iterate f x: [x,f x, f (f x), ...] repeat :: a -> [a] (infinite) ones from 1 types: type Vector = [Int] type Matrix = [Vector] classes: class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x==y) instance Eq Bool where True == True = True ... instance Eq a => Eq [a] where [] == [] = True (x:xs) == (y:ys) = x==y && xs=ys _ == _ = False class Eq a => Ord a where (<), (>), (<=), (>=) :: a -> a -> Bool max, min :: a -> a -> a class (Eq a, Show a) => Num a where (+), (-), (*) :: a -> a -> a data (algebraic data types): data Name = Constr Type1 Type2 | ... data Season = Winter | Spring | Summer | Fall data People = Person Name Age type People' = (Name, Age) type Name = String type Age = Int data Foo = D1 | D2 | D3 deriving (Eq, Ord, Enum, Show) data Expr = Lit Int | Add Expr Expr | Sub Expr Expr deriving (Show, Eq) eval :: Expr -> Int eval (Lit n) = n eval (Add e1 e2) = (eval e1) + (eval e2) eval (Sub e1 e2) = (eval e1) - (eval e2) trees: data Tree t = Leaf | Node t (Tree t) (Tree t) deriving (Eq, Show) treeSum :: Tree -> Int treeSum Leaf = 0 treeSum (Node n t1 t2) = n + (treeSum t1) + (treeSum t2) depth :: Tree -> Int depth Leaf = 0 depth (Node n t1 t2) = 1 + max (depth t1) (depth t2) with type variables (polymorphic functions!): data Pair t = MkPair t t MkPair 2 4 :: Pair Int MkPair [] [2,3] :: Pair [Int] MkPair [] [] :: Pair [t] equalPair :: Eq t => Pair t -> Bool equalPair (MkPair x y) = (x == y) treefold: treeFold :: (a -> b -> b -> b) -> b -> Tree a -> b treeFold f e Leaf = e treeFold f e (Node x l r) = f x (treeFold f e l) (treeFold f e r) to list: preorder t = treeFold (\x l r -> [x] ++ l ++ r) [] t inorder t = treeFold (\x l r -> l ++ [x] ++ r) [] t postorder t = treeFold (\x l r -> l ++ r ++ [x]) [] t duplicates: List.nub contains/element of: elem superstuff: functor: class Functor (f a) where fmap :: (a -> b) -> (f a) -> (f b) instance Functor List where fmap = mapList foldable: traversable: prelude: data Bool = False | True (&&), (||), not, otherwise data Maybe a = Nothing | Just a maybe :: b -> (a -> b) -> Maybe a -> b safeSecond :: [a] -> Maybe a safeSecond (_:x:_) = Just x safeSecond _ = Nothing data Either a b = Left a | Right b either :: (a -> c) -> (b -> c) -> Either a b -> c data Ordering = EQ | EQ | GT data Char Prelude.toEnum Prelude.fromEnum type String = [Char] fst, snd, curry, uncurry class Eq a where (==), (/=) class Eq a => Ord a where compare, (<), (>=), (>), (<=), max, min class Enum a where succ, pred, toEnum, fromEnum, enumFrom, enumFromThen, enumFromTo, enumFromThenTo class Bounded a where minBound, maxBound data Int fixed-precision integer type data Integer arbitrary-precision integer data Float data Double type Rational = Ratio Integer arbitrary-precision rational numbers, construct with % class (Eq a, Show a) => Num a where (+), (*), (-), negate, abs, signum, fromInteger class (Num a, Ord a) => Real a where toRational class (Real a, Enum a) => Integral a where quot, rem, div, mod, quotRem, divMod, toInteger class Num a => Fractional a where (/), recip, fromRational class Fractional a => Floating a where pi, exp, sqrt, log (**), logBase, sin, tan, cos, asin, atan, acos, sinh, tanh, cosh, asinh, atanh, acosh class (Real a, Fractional a) => RealFrac a where properFraction, truncate, round, ceiling, floor class (RealFrac a, Floating a) => RealFloat a where floatRadix, floatDigits, floatRange, decodeFloat, encodeFloat, exponent, significand, scaleFloat, isNaN, isInfinite, isDenormailzed, isNegativeZero, isIEEE, atan2 subtract, even, odd, gcd, lcm, (^), (^^), fromIntegral, realToFrac class Monad m where (>>=) :: forall a b. m a -> (a -> m b) -> m b (>>) :: forall a b. m a -> m b -> m b return :: a -> m a fail :: String -> m a required laws: return >>= k == k a m >>= return == m m >>= (\x -> k x >>= h) == (m >>= k) >>= h for monad and functors: fmap f xs == xs >>= return . f class Functor f where fmap :: (a -> b) -> f a -> fb laws: fmap id == id fmap (f . g) == fmap f . fmap g mapM: equiv to sequence . map f mapM_ sequence :: Monad m => [m a] -> m [a] sequence_ :: Monad m => [m a] -> m () (=<<) misc ops: id, const, (.), ($), until, asTypeOf, error, undefined, seq, ($!) switch/reverse/revert arguments: flip list ops: map, (++), filter, head, last, tail, init, null, length, (!!), reverse reducing lists/folds: foldl, foldl1, foldr, foldr1 and, or, any, all, sum, product, concat, concatMap, maximum, minimum scans: scanl, scanl1, scanr, scanr1 infinite lists: iterate, repeat, replicate, cycle sublists: take, drop, splitAt, takeWhile, dropWhile, span, break search: elem, notElem, lookup zipping: zip, zip3, zipWith, zipWith3, unzip, unzip3 strings: lines, words, unlines, unwords type ShowS = String -> String class Show a where showsPrec, show, showList shows, showChar, showString, showParen convert/parser: type ReadS a = String -> [(a, String)] class Read a where readsPrec, readList reads, readParen, read, lex io input/output: i/o can be performed only by binding it to Main.main data IO a output: putChar, putStr, putStrLn, print input: getChar, getLine, getContents, interact files: type FilePath = String readFile :: FilePath -> IO String writeFile appendFile readIO readLn exception handling: type IOError = IOException ioError, userError, catch interact: import System.Environment (getArgs) interactWith function inputFile outputFile = do input <- readFile inputFile writeFile outputFile (function input) main = mainWith myFunction where mainWith function = do args <- getArgs case args of [input,output] -> interactWith function input output _ -> putStrLn "error: exactly two arguments needed" -- replace "id" with the name of our function below myFunction = id data.list: (++), head, last, tail, init, null, length map, reverse, intersperse, intercalate, transpose, subequences, permutations foldl, foldl', foldl1, foldl1', foldr, foldr1 concat, concatMap, and, or, any, all, sum, product, maximum, minimum scanl, scan1, scanr, scanr1 mapAccumL, mapAccumR iterate, repeat, replicate, cycle unfoldr take, drop, splitAt, takeWhile, dropWhile, span, break, stripPrefix, group inits, tails isPrefixOf, isSuffixOf, isInfixOf elem, notElem, lookup find, filter, partition (!!), elemIndex, elemIndices, findIndex, findIndices zip, zip3, zip4, zip5, zip6, zip7 zipWith ... 7 unzip ... 7 lines, words, unlines, unwords set operations: nub, delete, (\\), union, intersect order: sort, insert nubBy, deleteBy, deleteFirstsBy, unionBy, intersectBy, groupBy sortBy, insertBy, maximumBy, minimumBy genericLength, genericTake, genericDrop, genericSplitAt, genericIndex, genericReplicate data.char: type String = [Char] isControl, isSpace, isLower, isUpper, isAlpha, isPrint, isDigit isOctDigit, isHexDigit, isLetter, isMark, isNumber, isPunctuation isSymbol, isSeparator isAscii, isLatin1, isAsciiUpper, isAsciiLower data GeneralCategory = UppercaseLetter | ... generalCategory toUpper, toLower, toTitle digitToInt, intToDigit ord, chr showLitChar, lexLitChar, readLitChar Language.Haskell.Parsere