import Data.List --------------------Indentare și paranteze insSort [] = [] insSort (x:xs) = ins x (insSort xs) -- aplicația de funcție are prioritate -- și e asociativă la stânga ins e [] = [e] ins e (x:xs) = -- erau necesare aceste paranteze? DA if e < x then e : x : xs else x : (ins e xs) -- dar acestea? NU --------------------Pattern matching fib :: Int -> Int fib 0 = 0 fib 1 = 1 fib n = fib (n-2) + fib (n-1) sumL :: [Int] -> Int sumL [] = 0 sumL (x:xs) = x + sumL xs --sumP :: (Int, Int) -> Int --mai elegant decât sumP p = fst p + snd p sumP (x,y) = x + y --ordered :: [Int] -> Bool ordered [] = True ordered [x] = True ordered (x:y:rest) = x <= y && ordered (y:rest) --ordered2 :: [Int] -> Bool ordered2 (x:xs@(y:rest)) = x <= y && ordered2 xs ordered2 _ = True --ex: map și filter cu PM --mapPM mapPM f [] = [] mapPM f (x:xs) = f x : mapPM f xs --filterPM filterPM p [] = [] filterPM p (x:xs) = if p x then x : filterPM p xs else filterPM p xs --nu funcționează (din cauză că pattern-urile nu pot fi potrivite și între ele) --eq x x = True -- eroare: Conflicting definitions for `x' --eq _ _ = False --------------------Expresii condiționale --uglySum :: [Int] -> Int uglySum l = if null l then 0 else head l + uglySum (tail l) --myTranspose :: [[a]] -> [[a]] -- [[1,2,3], [4,5,6], [7,8,9]] ===> -- [ [2,3], [5,6], [8,9]] ===> -- [ [3], [6], [9]] ===> -- [ [], [], []] myTranspose matrix = case (head matrix) of [] -> [] _ -> map head matrix : myTranspose (map tail matrix) --ex: myTranspose cu pattern matching myTransposePM ([]:_) = [] myTransposePM matrix = map head matrix : myTransposePM (map tail matrix) --ex: filter cu pattern matching și case --filterCase filterCase _ [] = [] filterCase p (x:xs) = case p x of True -> x : filterCase p xs _ -> filterCase p xs --allEqual :: Eq a => a -> a-> a-> Bool allEqual a b c | a==b = b==c | otherwise = False --ex: filter cu pattern matching și gărzi filterG p [] = [] filterG p (x:xs) | p x = x : filterG p xs | otherwise = filterG p xs --ex: filter cu pattern guards --filterPG filterPG p lst | [] <- lst = [] | x:xs <- lst, p x, let res = filterPG p xs = x : res | otherwise = filterPG p (tail lst) --------------------Legări locale -- Legările dintr-un let/where trebuie să fie aliniate -- (adică să înceapă pe aceeași coloană)! solveQuad a b c = let delta = b^2 - 4*a*c x1 = (-b + sqrt delta) / (2*a) x2 = (-b - sqrt delta) / (2*a) in (x1, x2) where sqrt = (**0.5) exwhere = a + b + c + d -- 16 where a = 2+5 -- a= 7 (b, c) = head (zip [1..] [2..]) --(b,c) = (1,2) d = f 5 -- 6 where f = (+1) --ex: filter cu pattern matching, gărzi și where filterAll _ [] = [] filterAll p (x:xs) | p x = x : rest | otherwise = rest where rest = filterAll p xs --ex: longestCommonPrefix a b c, folosind: -- take :: Int -> [a] -> [a] -- takeWhile :: (a -> Bool) -> [a] -> [a] longestCommonPrefix a b c = take len a where len = length (takeWhile id (zipWith3 allEqual a b c))