DEV Community

Discussion on: Daily Challenge #286 - Reverse It Quickly!

Collapse
 
cipharius profile image
Valts Liepiņš • Edited

Haskell solution in exactly 28 characters:

r=flip(:)`foldl`[]::[a]->[a]

Longer version of the same, but more readable:

myReverse :: [a] -> [a]
myReverse = flip (:) `foldl` []

Couldn't skip type annotations as that raises ambiguous type error.

Explanation:

  1. Function foldl applies a given function to all container elements going from inside out. When applied to list, it effectively traverses list in a reverse order.
  2. Binary operator foldl is applied to flip (:) and [].
  3. foldl has type signature Foldable t => (b -> a -> b) -> b -> t a -> b, which can be rewritten as ([a] -> a -> [a]) -> [a] -> [a] -> [a].
  4. Binary operator (:) appends a value (first argument) to a list (second argument). It's type signature is a -> [a] -> [a]. It almost looks like the required signature from the 3. point.
  5. Use the flip function in order to switch around (:) first and second argument. This results in a function flip (:) with type signature of [a] -> a -> [a].
  6. Now when this flip (:) is partially applied to foldl, it gives a function foldl (flip (:)) with a type signature [a] -> [a] -> [a]. Giving foldl a initial value of [], gives the final form foldl (flip (:)) [] with a type signature [a] -> [a].