Kihagyás

5. gyakorlat

Gyakorlás - (++), concat, elem, isPrefixOf, nub

Article

(++) :: [a] -> [a] -> [a]
(++) [] b = b
(++) (a:as) b = a:(as ++ b)
isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (a:as) (b:bs) = a == b && isPrefixOf as bs
concat :: [[a]] -> [a]
concat (x:xs) = x ++ concat xs
concat [] = []
elem :: (Eq a) => a -> [a] -> Bool
elem _ [] = False
elem a (x:xs) = x == a || elem a xs
nub :: (Eq a) => [a] -> [a]
nub [] = []
nub (x:xs) = x:nub [a | a <- xs, a /= x]
toUpperAll :: String -> String
toUpperAll [] = []
toUpperAll (x:xs) = toUpper x : toUpperAll xs

Őrfeltétel - Guards

fact :: Integer -> Integer
fact n
    | n <= 0     = 1
    | otherwise  = n * fact (n - 1)

fact' :: Integer -> Integer
fact' x | x <= 0 = 0
fact' x          = x * fact (x-1)

otherwise = True - literally

drop :: Int -> [a] -> [a]
drop _ []          = []
drop n ys@(_:xs)
    | n <= 0    = ys
    | otherwise = drop (n-1) xs
take :: Int -> [a] -> [a]
take _ [] = []
take n (x:xs)
    | n <= 0    = []
    | otherwise = x:take (n-1) xs
insert :: Ord a => a -> [a] -> [a]
insert a []      = [a]
insert a list@(x:xs)
    | a <= x     = a:list
    | otherwise  = x:insert a xs
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations n _ | n < 0 = []
combinations _ [] = []
combinations n (x:xs) = [x:ys | ys <- combinations (n-1) xs] ++ combinations n xs

Rekurzió: Olyan függvény ami önmaga definícióját használja fel önmaga definiálásához.