In [1]:
import Test.QuickCheck

In [2]:
length' :: [a] -> Int
length' [] = 0
length' (_:xs) = 1 + length' xs

In [8]:
palindromize [] = []
palindromize (x:xs) = [x] ++ palindromize xs ++ [x]
palindromize "AN"


"ANNA"

In [21]:
isPalindrome [] = True
isPalindrome (x:xs) = (x == last xs) && (isPalindrome $ init xs)


Move brackets to avoid $
Found:
(x == last xs) && (isPalindrome $ init xs)
Why Not:
(x == last xs) && isPalindrome (init xs)

In [6]:
interperse :: a -> [[a]] -> [a]
interperse _ [x] = x
interperse sep (x:xs) = x ++ [sep] ++ interperse sep xs

In [10]:
data Tree a = Node a (Tree a) (Tree a) | Empty
shallowTree = Node 1 (Node 2 Empty Empty) (Node 3 (Node 4 Empty Empty) Empty)

In [22]:
depth :: Tree a -> Int
depth Empty = 0
depth (Node _ left right) = 1 + max (depth left) (depth right)

In [23]:
depth shallowTree


3

In [11]:
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:_) = Just x

worksLikeHead xs
    | null xs = (safeHead xs) == Nothing
    | otherwise = (safeHead xs) == Just (head xs)
    
quickCheck worksLikeHead


+++ OK, passed 100 tests.

In [9]:
safeTail :: [a] -> Maybe [a]
safeTail [] = Nothing
safeTail (_:xs) = Just xs

worksLikeTail xs
    | null xs = (safeTail xs) == Nothing
    | otherwise = (safeTail xs) == Just (tail xs)
    
quickCheck worksLikeTail


+++ OK, passed 100 tests.

In [16]:
safeLast :: [a] -> Maybe a
safeLast [] = Nothing
safeLast [x] = Just x
safeLast (x:xs) = safeLast xs

worksLikeLast xs
    | null xs = (safeLast xs) == Nothing
    | otherwise = (safeLast xs) == Just (last xs)
    
quickCheck worksLikeLast


+++ OK, passed 100 tests.

In [10]:
import Data.List
import Data.Maybe

splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith _ [] = []
splitWith predicate xs = [left] ++ splitWith predicate right
    where
    right = fromMaybe [] (safeTail rest)
    (left, rest) = splitAt pos xs
    pos = fromMaybe (length xs) (findIndex predicate xs)

In [13]:
splitWith (== 'r') "aafafafraffars"


["aafafaf","affa","s"]

In [29]:
xs = [1,2,3,4]

In [31]:
findIndex (== 5) xs


Use elemIndex
Found:
findIndex (== 5)
Why Not:
elemIndex 5
Nothing

In [36]:
fromMaybe 100 (findIndex (==5) xs)


Use elemIndex
Found:
findIndex (== 5)
Why Not:
elemIndex 5
100

In [ ]: