new: Solved the first 10 problems
This commit is contained in:
parent
7645f6fcc5
commit
0cd5383b00
10 changed files with 59 additions and 1 deletions
|
@ -2,7 +2,7 @@
|
|||
myLast :: [a] -> a
|
||||
myLast [] = error "Empty list"
|
||||
myLast [s] = s
|
||||
myLast (hd : tl) = myLast tl
|
||||
myLast (_ : tl) = myLast tl
|
||||
|
||||
-- Alternative Solution using fold
|
||||
myLast' :: [a] -> a
|
||||
|
|
11
Problems 1-10/problem_10.hs
Normal file
11
Problems 1-10/problem_10.hs
Normal 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
|
||||
)
|
||||
[]
|
4
Problems 1-10/problem_2.hs
Normal file
4
Problems 1-10/problem_2.hs
Normal file
|
@ -0,0 +1,4 @@
|
|||
myButLast :: [a] -> a
|
||||
myButLast [] = error "List length less than 2"
|
||||
myButLast [a, _] = a
|
||||
myButLast (hd : tl) = myButLast tl
|
4
Problems 1-10/problem_3.hs
Normal file
4
Problems 1-10/problem_3.hs
Normal 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)
|
8
Problems 1-10/problem_4.hs
Normal file
8
Problems 1-10/problem_4.hs
Normal 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
|
2
Problems 1-10/problem_5.hs
Normal file
2
Problems 1-10/problem_5.hs
Normal file
|
@ -0,0 +1,2 @@
|
|||
myReverse :: [a] -> [a]
|
||||
myReverse = foldl (flip (:)) []
|
2
Problems 1-10/problem_6.hs
Normal file
2
Problems 1-10/problem_6.hs
Normal file
|
@ -0,0 +1,2 @@
|
|||
isPalindrome :: (Eq a) => [a] -> Bool
|
||||
isPalindrome = (==) <$> foldl (flip (:)) [] <*> id
|
6
Problems 1-10/problem_7.hs
Normal file
6
Problems 1-10/problem_7.hs
Normal 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
|
10
Problems 1-10/problem_8.hs
Normal file
10
Problems 1-10/problem_8.hs
Normal file
|
@ -0,0 +1,10 @@
|
|||
compress :: (Eq a) => [a] -> [a]
|
||||
compress =
|
||||
foldr
|
||||
( \x acc ->
|
||||
if acc /= []
|
||||
&& x == head acc
|
||||
then acc
|
||||
else x : acc
|
||||
)
|
||||
[]
|
11
Problems 1-10/problem_9.hs
Normal file
11
Problems 1-10/problem_9.hs
Normal 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
|
||||
)
|
||||
[]
|
Loading…
Reference in a new issue