简体   繁体   中英

Recursive functions that reverse a list in Haskell

I've been tasked to create a recursive function that takes in a list and gives the reverse of the list.

I have been able to create the a function named rev1 which does this:

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

But I have been asked to create a another function 'rev2' which should use an additional argument serving as an accumulator.

Could somebody please help me compose the rev2 function.

Thanks in advance, Sam

First of all, your rev1 should be this instead:

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

The point of rev2 would be to achieve tail recursion by means of passing the intermediate result inside an accumulator argument:

rev2 :: [a] -> [a] -> [a]
-- if applied to an empty list, just return the result
-- so far, i.e. whatever is inside the accumulator:
rev2 acc    []  =         acc
-- otherwise, take the head of the list and append it to
-- the accumulator, and carry on with the rest of the list
rev2 acc (x:xs) = rev2 (x:acc) xs

this, however, obviously has the downside of exposing the acc argument to users of rev2 , so a typical approach is hiding the accumulator based implementation behind a façade that looks exactly like rev1 :

rev2 :: [a] -> [a]
rev2 xs = go [] xs where
  go :: [a] -> [a] -> [a]  -- signature included for clarity
  go acc    []  =       acc
  go acc (x:xs) = go (x:acc) xs

Let me start things off:

rev2 :: [a] -> [a]
rev2 xs = rev2' xs ???

rev2' :: [a] -> [a] -> [a]
rev2' [] ys = ???
rev2' (x : xs) ys = ???

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM