Recursive functions that reverse a list in Haskell -
i've been tasked create recursive function takes in list , gives reverse of list.
i have been able create function named rev1
this:
rev1 :: [a] -> [a] rev1 [] = [] rev1 (x:xs) = reverse xs ++ [x]
but have been asked create function 'rev2' should use additional argument serving accumulator.
could please me compose rev2
function.
thanks in advance, sam
first of all, rev1
should instead:
rev1 :: [a] -> [a] rev1 [] = [] rev1 (x:xs) = rev1 xs ++ [x]
the point of rev2
achieve tail recursion means of passing intermediate result inside accumulator argument:
rev2 :: [a] -> [a] -> [a] -- if applied empty list, return result -- far, i.e. whatever inside accumulator: rev2 acc [] = acc -- otherwise, take head of list , append -- accumulator, , carry on rest of list rev2 acc (x:xs) = rev2 (x:acc) xs
this, however, has downside of exposing acc
argument users of rev2
, typical approach hiding accumulator based implementation behind façade looks rev1
:
rev2 :: [a] -> [a] rev2 xs = go [] xs go :: [a] -> [a] -> [a] -- signature included clarity go acc [] = acc go acc (x:xs) = go (x:acc) xs
Comments
Post a Comment