-- Tuples nullPoint :: (Float,Float) nullPoint = (0,0) distancea :: (Float,Float) -> (Float,Float) -> Float distancea a b = sqrt( dx*dx + dy*dy ) where dx = fst(a) - fst(b) dy = snd(a) - snd(b) distanceb :: (Float,Float) -> (Float,Float) -> Float distanceb (xa,ya) (xb,yb) = sqrt( dx*dx + dy*dy ) where dx = xa - xb dy = ya - yb roots :: Float -> Float -> Float -> (Float, Float) roots a b c = ( (-b-sd)/n, (-b+sd)/n ) where sd = sqrt(b*b - 4*a*c) n = 2*a -- New type type Vector2D = (Float,Float) sumVec :: Vector2D -> Vector2D -> Vector2D sumVec (x1,y1) (x2,y2) = (x1+x2,y1+y2) scalarProd :: Vector2D -> Vector2D -> Float scalarProd (x1,y1) (x2,y2) = x1*x2 + y1*y2 -- Enums data Tribool = Yes | No | Unknown toInt :: Tribool -> Int toInt Yes = 1 toInt No = -1 toInt Unknown = 0 tnot :: Tribool -> Tribool tnot Yes = No tnot No = Yes tnot Unknown = Unknown -- CharOrInt data CharOrInt = CharT Char | IntT Int squarePos :: CharOrInt -> CharOrInt squarePos v@(IntT x) | x > 0 = IntT (x*x) | otherwise = v squarePos v = v -- Trees data BinTreeA = LeafA Int | BinTreeA Int BinTreeA BinTreeA data BinTree = Leaf {value :: Int} | BinTree { value :: Int, left, right :: BinTree } depth :: BinTree -> Int depth (Leaf _) = 0 depth (BinTree _ l r ) = max (depth l + 1) (depth r + 1) size :: BinTree -> Int size (Leaf _) = 1 size (BinTree _ l r ) = (size l) + 1 + (size r) summ :: BinTree -> Int summ (Leaf v) = v summ (BinTree v l r ) = (summ l) + v + (summ r) minValue :: BinTree -> Int minValue (Leaf v) = v minValue (BinTree v l r ) = min3 v (minValue l) (minValue r) incValues :: BinTree -> BinTree incValues (Leaf value) = Leaf (value + 1) incValues (BinTree value left right) = BinTree (value + 1) (incValues left) (incValues right) replaceValues :: Int -> Int -> BinTree -> BinTree replaceValues from to leaf@(Leaf value ) | from == value = Leaf to | otherwise = leaf replaceValues from to tree@(BinTree value left right) | from == value = BinTree to (replaceValues from to left) (replaceValues from to right) | otherwise = tree{ left = replaceValues from to left, right = replaceValues from to right } sumTrees :: BinTree -> BinTree -> BinTree sumTrees (BinTree va la ra) (BinTree vb lb rb) = BinTree (va+vb) (sumTrees la lb) (sumTrees ra rb) sumTrees a b = Leaf ((value a)+(value b)) eqTrees :: BinTree -> BinTree -> Bool eqTrees (Leaf va) (Leaf vb) = va == vb eqTrees (BinTree va la ra) (BinTree vb lb rb) = va == vb && (eqTrees la lb) && (eqTrees ra rb) -- Trees and functionals collapseTree :: (Int -> Int -> Int -> Int) -> BinTree -> Int collapseTree _ (Leaf v) = v collapseTree f (BinTree v l r ) = f v (collapseTree f l) (collapseTree f r) mapTree :: (Int -> Int) -> BinTree -> BinTree mapTree f (Leaf value) = Leaf (f value) mapTree f (BinTree value left right) = BinTree (f value) (mapTree f left) (mapTree f right) -- Helpers min3 a b c | a <= b && a <= c = a | b <= a && b <= c = b | otherwise = c