Difference between revisions of "99 questions/Solutions/5"

From HaskellWiki
Jump to navigation Jump to search
 
m
 
(6 intermediate revisions by 4 users not shown)
Line 6: Line 6:
 
</haskell>
 
</haskell>
   
The standard definition is concise, but not very readable. Another way to define reverse is:
+
The standard definition, found in the prelude, is concise, but not very readable. Another way to define reverse is:
   
 
<haskell>
 
<haskell>
Line 23: Line 23:
 
reverse' (x:xs) reversed = reverse' xs (x:reversed)
 
reverse' (x:xs) reversed = reverse' xs (x:reversed)
 
</haskell>
 
</haskell>
  +
  +
And my favorite, although the most unreadable for sure :)
  +
  +
<haskell>
  +
myReverse'' :: [a] -> [a]
  +
myReverse'' xs = foldr (\x fId empty -> fId (x : empty)) id xs []
  +
</haskell>
  +
  +
Another foldl version:
  +
<haskell>
  +
myReverse''' :: [a] -> [a]
  +
myReverse''' = foldl (\a x -> x:a) []
  +
</haskell>
  +
<br>
  +
  +
[[Category:Programming exercise spoilers]]

Latest revision as of 12:06, 11 August 2017

(*) Reverse a list.

reverse          :: [a] -> [a]
reverse          =  foldl (flip (:)) []

The standard definition, found in the prelude, is concise, but not very readable. Another way to define reverse is:

reverse :: [a] -> [a]
reverse [] = []
reverse (x:xs) = reverse xs ++ [x]

However this definition is more wasteful than the one in Prelude as it repeatedly reconses the result as it is accumulated. The following variation avoids that, and thus computationally closer to the Prelude version.

reverse :: [a] -> [a]
reverse list = reverse' list []
  where
    reverse' [] reversed     = reversed
    reverse' (x:xs) reversed = reverse' xs (x:reversed)

And my favorite, although the most unreadable for sure :)

myReverse'' :: [a] -> [a]
myReverse'' xs = foldr (\x fId empty -> fId (x : empty)) id xs []

Another foldl version:

myReverse''' :: [a] -> [a]
myReverse''' = foldl (\a x -> x:a) []