Funkcionálne programovanie
data Pos = Pos Int Int
data Board = Board
Pos -- size
Int -- number of mines
[Pos] -- mines
[Pos] -- opened tiles
[Pos] -- marked tiles
boardSize :: Board -> Pos
boardSize (Board size _ _ _ _) = size
markTile :: Board -> Pos -> Board
markTile (Board size num mines opened marked) pos =
Board size num mines opened (pos:marked)
data Pos = Pos { posRow :: Int , posCol :: Int }
data Board = Board
{ boardSize :: Pos
, boardNumMines :: Int
, boardMines :: [Pos]
, boardOpened :: [Pos]
, boardMarked :: [Pos]
}
boardSize :: Board -> Pos
markTile :: Board -> Pos -> Board
markTile board pos =
board { boardMarked = pos:(boardMarked board) }
openedAndMarked :: Board -> ([Pos], [Pos])
openedAndMarked
(Board { boardOpened=o, boardMarked=m }) = o, m
int times(int x, int y) {
return x * y;
}
String times(int n, String s) {
return StringUtils.repeat(s, n);
}
class List<T>
(Java)data List a
(Haskell)class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
instance Eq Point where
(Point x1 y1) == (Point x2 y2) = x1 == x2 && y1 == y2
a /= b = not (a == b)
class Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
x == y = not (x /= y)
elem :: ?
elem x [] = False
elem x (y:ys) = x==y || (elem x ys)
elem :: a -> [a] -> Bool
elem x [] = False
elem x (y:ys) = x==y || (elem x ys)
elem :: (Eq a) => a -> [a] -> Bool
elem x [] = False
elem x (y:ys) = x==y || (elem x ys)
instance Eq a => Eq (List a) where
Nil == Nil = True
Cons x xs == Cons y ys = x == y && xs == ys
_ == _ = False
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>=), (>) :: a -> a -> Bool
max, min :: a -> a -> a
Nie elem :: Eq -> [Eq] -> Bool
,
ale elem :: (Eq a) => a -> [a] -> Bool
+
, -
, *
div
, mod
/
sin
, cos
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor List where
fmap op Nil = Nil
fmap op (Cons x xs) = Cons (op x) (fmap op xs)
f
nie je konkrétny typ, ale typový koštruktor:k
Int :: *
— konkrétny typMaybe :: * -> *
— typový konštruktorEither :: * -> * -> *
List :: * -> *
List Int :: *
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor List where
fmap op Nil = Nil
fmap op (Cons x xs) = Cons (op x) (fmap op xs)
Monad
… neskôrFoldable
: foldr
, foldl
elem
v skutočnosticlass Foldable t where
...
elem :: Eq a => a -> t a -> Bool
elem = any . (==)
...
data Shape = Circle Point Double
| Rectangle Point Point
deriving (Eq, Ord, Show)