diff --git a/4.hs b/4.hs index f1a2ef9..647c708 100644 --- a/4.hs +++ b/4.hs @@ -1 +1,7 @@ -- Find the number of elements of a list. + +myLength :: [a] -> Int +myLength [] = 0 +myLength (x:xs) = 1 + myLength xs + +main = print (myLength [1..100]) diff --git a/5.hs b/5.hs new file mode 100644 index 0000000..de0b782 --- /dev/null +++ b/5.hs @@ -0,0 +1,8 @@ +-- Reverse a list. + +myReverse :: [a] -> [a] +myReverse [] = [] +myReverse [x] = [x] +myReverse (x:xs) = (myReverse xs) ++ [x] + +main = print (myReverse [1..10]) diff --git a/6.hs b/6.hs new file mode 100644 index 0000000..9e6e060 --- /dev/null +++ b/6.hs @@ -0,0 +1,7 @@ +-- Find out whether a list is a palindrome. A palindrome can be read forward +-- or backward; e.g. (x a m a x). + +myPalindrome :: Eq a => [a] -> Bool +myPalindrome xs = xs == reverse xs + +main = print (myPalindrome "racecar") diff --git a/7.hs b/7.hs new file mode 100644 index 0000000..385f72c --- /dev/null +++ b/7.hs @@ -0,0 +1,10 @@ +-- Flatten a nested list structure. + +data NestedList a = Elem a | List [NestedList a] + +myFlatten :: NestedList a -> [a] +myFlatten (Elem x) = [x] +myFlatten (List []) = [] +myFlatten (List (x:xs)) = myFlatten x ++ myFlatten (List xs) + +main = print (myFlatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]]))