You also could use foldl
. the logic is: comparing the last element of accumulator with current element.
f :: Eq a => [a] -> [a]
f xs = foldl (\x y -> if last x == y then x else x++[y] ) [head xs] xs
here we initiate our accumulator with [head x]
.
Based on @dfeuer hint I change my solution:
-- with foldl
f :: Eq a => [a] -> [a]
f xs = snd $ foldl opr (Nothing, []) xs
where
opr (Just old, acc) n
| old == n = (Just old, acc)
| otherwise = (Just n, acc ++ [n])
opr (Nothing, acc) n = (Just n, acc ++ [n])
-- with foldr
f2 :: Eq a =>[a] -> [a]
f2 xs = snd $ foldr opr (Nothing, []) xs
where
opr n (Just old, acc)
| old == n = (Just old, acc)
| otherwise = (Just n, n:acc)
opr n (Nothing, acc) = (Just n, n:acc)
Thanks to @dfeuer, I learned a lot of new things. This is the third version based on comments:
-- with foldl
f :: Eq a => [a] -> [a]
f xs = snd $ foldl opr (Nothing, []) xs
where
opr (old, acc) n =
( Just n,
case old of
Just o
| o == n -> acc
| otherwise -> acc ++ [n]
Nothing -> acc ++ [n]
)
-- with foldr
f :: Eq a => [a] -> [a]
f xs = snd $ foldr opr (Nothing, []) xs
where
opr n (old, acc) =
( Just n,
case old of
Just o
| o == n -> acc
| otherwise -> n : acc
Nothing -> n : acc
)