Skip to content

Latest commit

 

History

History
447 lines (432 loc) · 31.3 KB

Haskell.org

File metadata and controls

447 lines (432 loc) · 31.3 KB

Haskell

#Datatypes
#Modules
#Types
#Pattern-Matching
#where-bindings
#let-bindings
#Guards
#Case-expressions
#currying
#lambda
#Function-application
#Function-composition
#own-datatypes
#I/O
#Random
#Exceptions
#do-notation
#Reader
#Standard-library-modules
#Resources

Datatypes

Datatypeinfo
IntNumber
IntegerInt with no bounds
FloatFloating Point
DoubleBigger Float
BoolTrue or False
CharCharacter

TypeClasses

TypeExplanation
OrdOrder-able
EqEquality testable
Numany Number
Integralonly whole numbers
FloatingFlaot, Double
OrderingGT, LT, EQ
ShowString-able
ReadCan be read from String
Enumenumerate-able
BoundedHave lower, upper bound
FunctorCan be mapped over

Modules

import modules

import module_name
import qualified mod1 as m1 -- when function names already exist in other modules use qualified, then rename mod1.func to m1.func
import mod1 (func1, func2) -- only import some functions
import mod1 hiding (func3) -- import everything except func3

import Folder_name.Own_module_name

create modules

module Module_name
(exported_func1,
 exported_func2,
) where

exported_func1 :: Num -> Num
...
exported_func2 ...
...
not_exported_func0 ...
...
module Folder_name.Own_module_name

Pattern Matching

scnd :: (a, b, c) -> a
scnd (_, x, _) = x

where bindings

`where` clause can be used to define local variables or functions at the end of a function. Variables defined in the `where` clause are visible inside the function as well as across guards. two different ways of writing where clauses:

where x = 1
    y = 2
    x = 3
where (x, y, z) = (1, 2, 3)

let bindings

`let` lets you bind local variables or functions to be used after `in`. If there is no `in` part, it will be visible in the current scope.

let x = 1
    y = 2
in x + y
[let square x = x*x in (square 1, square 2, square 3)]

Guards

like if else case

nums :: (Num a) => a -> a -> a
nums x y
    | z < 1 = 0
    | z < 3 = ret_one
    | otherwise = 2
    where z = x+y
        ret_one = 1

if `otherwise` is missing, the function will fall through (if there are any more)

Case expressions

like switch case with pattern matching

head' :: [a] -> a
head' xs = case xs of [] -> error "is empty"
            (x:_) -> x

currying

writing functions that await another parameter with the parameter behind it

3 + 4
(+ 4) 3
sum [1,2,3,4]
foldl (+) 0 [1,2,3,4]

lambda

inline function

func2 = map addNums [(1,2), (3,4), (5,6)]
    where addNums (a, b) = a + b
func1 = map (\(a,b) -> a + b) [(1,2), (3,4), (5,6)]

Function application

$ … as a shorter way of writing (…)

sqrt (3 + 4 + 9)
sqrt $ 3 + 4 + 9

f (g (z x))
f $ g $ z x

map ($ 3) [(4+), (10*), (^2), sqrt]

Funciton composition

(.) :: (b -> c) -> (a -> b) -> a -> c
f . g = \x -> f (g x)
map (\x -> negate (abs x)) [5,-3,-6,7,-3,2,-19,24]
map (negate . abs) [5,-3,-6,7,-3,2,-19,24]

own datatypes

type aliases/synonyms

type Name = String
type Number = String
type PhoneBook = [(Name, Number)]

type paramType x y = [(x, y)]

using data keyword

create a new datatype called Shape that can be either a Circle or a Rectangle consisting of 3/4 Flaot types

data Shape = Circle Float Float Float | Rectangle Float Float Float Float
data Shape2 = Shape2 Float deriving (Show) -- make type printable
data Shape3 a = Shape3 a a -- parameterized type
data Shape4 = Shape4 { x :: Float, y :: Float } -- will create functions x and y that return a Float

using newtype keyword

newtype is faster then data but can only have one value constructor with one field

newtype CharList = CharList { getCharList :: [Char] } deriving (Eq, Show)

export datatype

module Module_name
( Shape(...) -- ... exports all value constructors
) where

define typeclasses

class Eq a where
    (==) :: a -> a -> Bool
    (/=) :: a -> a -> Bool
    x == y = not (x /= y)
    x /= y = not (x == y)

define used typeclass

instance Show Shape where
show Circle x y z = x ++ " " ++ y ++ " " ++ z

I/O

Hello World

main = putStrLn "Hello World!"

Hello name

main = do
    putStrLn "Whats your name?"
    name <- getLine
    putStr ("Hello " ++ name ++ "!")

output input

main = do
    line <- getLine
    if null line -- has to be if condition then I/O action else I/O action
        then return ()        -- I/O action that does nothing
        else do
            putStrLn line     -- I/O action that prints the line
            return "next"     -- I/O action that does nothing
            a <- return "next"-- I/O action that binds "next" to a
            main              -- I/O action

Random

random (mkStdGen 1) :: (Int, StdGen) -- have to specify the return type

Exceptions

main = toTry handler

toTry :: IO ()
toTry = do (fileName:_) <- getArgs
    contents <- readFile fileName
    putStrLn $ show (length (lines contents)) ++ " lines"

handler :: IOError -> IO ()
handler e
    | isDoesNotExistError e = putStrLn "file missing"
    | otherwise = ioError e -- throw Exception if catched wrong one

do notation

foo :: Maybe String
foo = Just 3 >>= (\x ->
Just "!" >>= (\y ->
Just (show x ++ y)))
foo :: Maybe String
foo = do
    x <- Just 3
    y <- Just "!"
    Just (show x ++ y)

Reader

addStuff :: Int -> Int
addStuff x = let
    a = (*2) x
    b = (+10) x
    in a+b
addStuff :: Int -> Int
addStuff = do
    a <- (*2)
    b <- (+10)
    return (a+b)

Standard library modules

modulefunctionexplanation
fmap f xsgeneric map
putStrLntakes String and a new line and returns an IO action
putStrtakes String (without a new line) an IO action
putChar
printcall putStrLn with the stringified variable
getLinereturns IO action from IO
getChar
sequence xscalls all functions in list xs
mapM f xsmap function f to every element in list xs and returns IO action
mapM_ f xssame as mapM but throws away the result
getContentsread from stdin until EOF
interact fstdin into f into stdout
Data.List
head xsgive first element of list xs
length xsget length of a list
takeWhile f xstake elements of xs into a new list as long as f is true (takeWhile (<1000) [1..])
dropWhile f xstake elements of xs into a new list starting when f is true
span f xsreturns pair of lists that would have been returned b takeWhile, dropWhile
break f xssame as span (not . f) xs
sum xsget sum of list xs
map f xsmap function f to every element in list xs
flip x yflip input values to y x
foldl f 0 xsapply function f over list (from the left) xs with the starting value 0
foldl1 f xsapply function f over list (from the left) xs with the starting value of x:xs
foldr f 0 xsapply function f over list (from the right) xs with the starting value 0
foldr1 f xsapply function f over list (from the right) xs with the starting value of xs:x
scanl,scanl1,scanr,scanr1like foldl,foldl1,foldr,foldr1 but will give a list of all intermediate values
intersperse ‘.’ xsput a ‘.’ in between every element of the list xs
concat xsflatten list of lists
intercalate xs tsput list xs in between all lists of ts and flatten the result
transpose xsswitch columns and rows of the 2D matrix xs
and= &&
or
union
intersect
any f xsreturn True if any element of xs satifies f
all f xsreturn True if all alements of xs satify f
iterate f xreturn infinite list [f(x), f(f(x)), …]
splitAt x xssplit list xs into tuple at index x
sort xssort list xs
group xsgroup following, equal list items
isInfixOf xs tsreturn if xs is in ts
isPrefixOf xs tsreturn if xs is in the beginning of ts
isSuffixOf xs tsreturn if xs is at the end of ts
partition f xsreturn pair of lists that match f, don’t match f
find f xsreturns the first element of xs that satisfies f
findIndex f xsreturns the index of the first element of xs that satisfies f
findIndeces f xsreturns a list of indeces of xs that satisfy f
elem x xsreturns wether x is an element in xs
elemIndex x xsreturns the index of x, if x is an element in xs
elemIndeces x xsreturns a list of indeces of all elements x in xs
zip xszip together two lists in a touple (also zip3, zip4, … zip7)
zipWith f xszip together two lists using f also (zipWith3, … zipWith7)
lines xsreturn list of all xs seperated by lines
unlines xsreverse lines
words xssame as lines but split at ’ ’
unwords xsreverse words
nub xsremove duplicates from xs
delete x xsdelete the first case of x in xs
xs \ tscalls delete for every in element in ts on xs
insert x xsinsert x in xs at the left of the first bigger element (from left)
xs !! iget the element at index i of the list xs
genericIndexmore generic !!
genericLength xsreturns Num instead of Int (length xs)
nubBy f xssame as nub but usees f for comparison
on f g= \x y -> f(g x) (g y)
Data.Char
isControl xx is a control character
isSpace, …x is a … character
generalCategory xget the general Category of char x
toLower xconvert character x to lower case
digitToInt xturn character x into an Integer (0-F)
Data.Map
fromList [(x, y), …]returns Map Object from input
singleton x yfromList [(x, y)]
insert x y minsert (x, y) into Map m
null mcheck if m is empty
size mget m size
member x mcheck if x is a member of m
map, filterlike normal map and filter
fromListWith f xslike fromList but function f decides what to do with duplicate keys
lookup x mlookup value of key x in Map m
Data.Setno duplicates
fromList xslike Data.Map.fromList
intersection s1 s2
difference s1 s2
union s1 s2
many of the same functions as in Data.Map
Control.Monad
when cond $ f
forever fcalls f forever
forM xs flike mapM with switched arguments
System.IO
openFile file modereturns IO Handle to file using mode (ReadMode, WriteMode, AppendMode, ReadWriteMode)
hGetContents handlelike getContents but uses IO Handle instead of stdin
hClose handlereturns IO action that closes the file
withFile file mode flike openFile, sends its Handle to f (which has to return an IO action), closes Handle
hGetLine
hPutStrLn
readFile filereads file, returns IO String
writeFile file strwrites str to file
appendFile file str
hSetBuffering handle modechange buffer method/size
hFlush handleflushes Handle
openTempFile dir file_namecreate temp file file_name… in dir, returns (FilePath, IO Handle)
System.IO.Error
catch IOf fif IOf throws an IOError, the Handler f then decides what to do
ioeGetFileName etakes IOError and returns Maybe FilePath
System.Directory
removeFile file
renameFile file to
System.Environment
getArgsget input arguments as [String]
getProgNameget program name
System.Random
random gentakes a RandomGen and returns (Random, RandomGen)
randoms gentakes gen and returns infinite sequence of values
randomR (l,u) gensame as random but takes (lower,upper) bounds
getSdtGenreturns RandomGen as IO action from OS
Data.Bytestringno lazynes, no promisses(thunks), just a string of bytes
pack xspack values into Bytestring
unpack bunpack bytestring b
fromChunks btake Bytestring and convert it into a lazy Bytestring
cons x bx:b, will create a new chunk everytime
cons’ x bx:b, will not create a new chunk everytime
head, tail, map, …
readFile filesame as System.IO but will return IO Bytestring
Data.Bytestring.Lazysame as Data.Bytestringstorage in chunks of 64K
toChunks bturn lazy Bytestring into Bytestring
Control.Applicativeadds typeclass Applicative
pure xneeded for <*>
f <*> xpure (+) <*> [1,2,3] <*> [100,200,300] = [101,201,301,201,202,…]
f <$> xsfmap f xs
ZipList xs(+) <$> ZipList [1,2,3] <*> ZipList [100,200,300] = [101, 202, 303] {FIXME: TODO!!!}
getZipList xsshow ZipList
liftA2 f x tlike <*> with extra argument
Data.Monoidadds typeclass Monoid
mappend x ytakes two monoids and returns a third (*, ++, -, …)
memptyrepresents identity value for a monoid (1, [], 0, …)
mconcat xstakes a list of monoids and applies mappend between all elements
Data.Foldable
foldMap f xmap function f (that returns monoid) over foldable structure x and returns single monoid
foldr …like normal foldr but takes Foldable instead of a list (free when implementing foldMap)
Control.Monadadds typeclass Monad
x >>= fextracts value from x and applies it to f, returns that using x’s context
x >> yfor Maybe: returns Nothing, if x or y = Nothing else returns y
failhas to be described when creating an instance: fail value
guard f xonly let values x through that satisfy f
liftM f mlike fmap for monads
liftM2,…,liftM5like liftM for more values
ap mf mlike <*>, but the function is wrapped in a monad
join mmaflattens a Monadic value wrapped inside of Monad(s)
filterM f xslike filter but f returns a Monad
foldM f 0 xslike foldl but f returns a Monad
<=<like (.) for Monads
Control.Monad.Writeradds type Writer (used for logging)
Writer (x, xs)create a Writer with value x and message xs
runWriter xunpack Writer into tuple
tell xsadd xs to current Writer
Control.Monad.Instances
->
Control.Monad.Stateadds type MonadState
get stakes State s and presents it as a result
Control.Monad.Erroradds type Either (Left/Right) = (Failure/Success). Have to be in Error typeclass
Data.Rationaladds type Rational: numerator % denominator

Resources

https://hoogle.haskell.org/ http://learnyouahaskell.com