new: Solved the first 10 problems

This commit is contained in:
Sayantan Santra 2024-05-24 17:06:42 -05:00
parent 7645f6fcc5
commit 0cd5383b00
Signed by: SinTan1729
GPG key ID: EB3E68BFBA25C85F
10 changed files with 59 additions and 1 deletions

View file

@ -2,7 +2,7 @@
myLast :: [a] -> a myLast :: [a] -> a
myLast [] = error "Empty list" myLast [] = error "Empty list"
myLast [s] = s myLast [s] = s
myLast (hd : tl) = myLast tl myLast (_ : tl) = myLast tl
-- Alternative Solution using fold -- Alternative Solution using fold
myLast' :: [a] -> a myLast' :: [a] -> a

View file

@ -0,0 +1,11 @@
encode :: (Eq a, Num n) => [a] -> [(n, a)]
encode =
foldr
( \x acc -> case acc of
[] -> [(1, x)]
(hd@(hd_n, hd_a) : tl) ->
if x == hd_a
then (hd_n + 1, hd_a) : tl
else (1, x) : hd : tl
)
[]

View file

@ -0,0 +1,4 @@
myButLast :: [a] -> a
myButLast [] = error "List length less than 2"
myButLast [a, _] = a
myButLast (hd : tl) = myButLast tl

View file

@ -0,0 +1,4 @@
elementAt :: (Num n, Eq n) => [a] -> n -> a
elementAt [] _ = error "Invalid index"
elementAt (hd : _) 1 = hd
elementAt (_ : tl) k = elementAt tl (k - 1)

View file

@ -0,0 +1,8 @@
-- Simple recursive solution
myLength :: (Num n) => [a] -> n
myLength [] = 0
myLength (_ : tl) = 1 + myLength tl
-- Solution using fold
myLength' :: (Num n) => [a] -> n
myLength' = foldl (\acc _ -> acc + 1) 0

View file

@ -0,0 +1,2 @@
myReverse :: [a] -> [a]
myReverse = foldl (flip (:)) []

View file

@ -0,0 +1,2 @@
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome = (==) <$> foldl (flip (:)) [] <*> id

View file

@ -0,0 +1,6 @@
data NestedList a = Elem a | List [NestedList a]
flatten :: NestedList a -> [a]
flatten x = case x of
Elem e -> [e]
List l -> concatMap flatten l

View file

@ -0,0 +1,10 @@
compress :: (Eq a) => [a] -> [a]
compress =
foldr
( \x acc ->
if acc /= []
&& x == head acc
then acc
else x : acc
)
[]

View file

@ -0,0 +1,11 @@
pack :: (Eq a) => [a] -> [[a]]
pack =
foldr
( \x acc -> case acc of
[] -> [[x]]
(hd : tl) ->
if x == head hd
then (x : hd) : tl
else [x] : hd : tl
)
[]