Skip to content

Instantly share code, notes, and snippets.

@kamoshi
Created July 5, 2022 12:51
Show Gist options
  • Save kamoshi/64944a3bf4f29a9939927ee843bde2b2 to your computer and use it in GitHub Desktop.
Save kamoshi/64944a3bf4f29a9939927ee843bde2b2 to your computer and use it in GitHub Desktop.
Haskell solutions to Scala exercises
-- Lista 0
last' :: [a] -> Maybe a
last' [] = Nothing
last' [x] = Just x
last' (_:xs) = last' xs
-- Lista 1
suma :: [Double] -> Double
suma [] = 0
suma (x:xs) = x + suma xs
ends :: [a] -> Maybe (a, a)
ends [] = Nothing
ends [x] = Just (x, x)
ends (x:xs) = last' xs >>= \end -> Just (x, end)
posortowana :: [Int] -> Bool
posortowana [] = True
posortowana [x] = True
posortowana (x1:x2:xs) = x1 < x2 && posortowana (x2:xs)
glue :: [String] -> Char -> String
glue [] _ = ""
glue [x] _ = x
glue (x:xs) c = x ++ [c] ++ glue xs c
-- Lista 2
take' :: Int -> [a] -> [a]
take' _ [] = []
take' n (x:xs) = if n <= 0 then [] else x : take (n-1) xs
drop' :: Int -> [a] -> [a]
drop' _ [] = []
drop' n (x:xs) = if n <= 0 then x:xs else drop' (n-1) xs
reverse' :: [a] -> [a]
reverse' xs = helper xs []
where
helper [] acc = acc
helper (x:xs) acc = helper xs (x:acc)
replicate' :: [Int] -> [Int]
replicate' [] = []
replicate' (x:xs) = helper x x ++ replicate' xs
where
helper x n = if n <= 0 then [] else x : helper x (n-1)
root3 :: Double -> Double
root3 a = helper (if a > 1 then a/3 else a)
where
helper xi = let e = 10 ^^ (-15) in
if abs (xi ^ 3 - a) <= e * abs a then xi else helper (xi + (a / (xi ^ 2) - xi) / 3)
-- Lista 3
existsA :: [a] -> (a -> Bool) -> Bool
existsB :: [a] -> (a -> Bool) -> Bool
existsC :: [a] -> (a -> Bool) -> Bool
existsA [] _ = False
existsA (x:xs) p = p x || existsA xs p
existsB xs p = foldl (\ acc next -> acc || p next) False xs
existsC xs p = foldr (\ next acc -> acc || p next) False xs
filter' :: [a] -> (a -> Bool) -> [a]
filter' xs p = foldr (\ next acc -> if p next then next : acc else acc) [] xs
remove1A :: [a] -> (a -> Bool) -> [a]
remove1B :: [a] -> (a -> Bool) -> [a]
remove1A [] _ = []
remove1A (x:xs) p = if p x then xs else x : remove1A xs p
remove1B xs p = helper xs p []
where
helper [] _ acc = acc
helper (x:xs) p acc = if p x then helper [] p (reverse acc ++ xs) else helper xs p (x:acc)
splitAt' :: [a] -> Int -> ([a], [a])
splitAt' xs n = helper xs n []
where
helper [] _ acc = ([], acc)
helper (x:xs) n acc = if n <= 0 then (reverse acc, x:xs) else helper xs (n-1) (x:acc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment