Reversing a string (or list) recursively
I'm trying to write a function in haskell that reverses lists recursively. I wrote a helper function that takes the original list and an empty list then transfers elements from the first one to the other in a LIFO pattern.
Here's what I开发者_如何学运维 have:
myreverse :: [a] -> [a]
myreverse list = myflip list []
myflip :: [a] -> [a] -> [a]
myflip list1 newList
| null list1 = newList
| otherwise = myflip (tail list1) ((head list1) : newList)
I know there's a built-in function that does it for me but the requirement is that I only use head, tail, elem and null (No pattern matching either). So my question is: is there a better solution where I only have one function, myreverse, that consumes only one list? (That meets the requirements above, of course)
Thanks!
You can try reversing a list using foldl
like so:
reverse' :: [a] -> [a]
reverse' = foldl (\acc x -> x : acc) []
So for anyone who might be interested, this is what I ended up writing:
myreverse :: [a] -> [a]
myreverse list = myflip list []
where myflip list newList = if null list then newList
else myflip (tail list) ((head list):newList)
Thanks everyone for your comments and suggestions.
save this in reverse.hs file
reverseString :: [Char] -> [Char]
reverseString [] = []
reverseString (x:xs) = reverseString xs ++ [x]
then run reverseString "abc"
cba
Aside from the adjustments necessary to meet your additional requirements, your function is equivalent to the way reverse
is implemented in GHC. Therefore I'd assume your function is pretty good the way it is.
This function fulfills your requirements, but is horrible inefficient:
rev xs = if null xs then xs else rev (tail xs) ++ [head xs]
Your solution isn't bad at all. After using pattern matching and making myFlip
a local function it wouldn't look ugly. And the technique of using a local function with an accumulator is very common (although not in such easy cases).
精彩评论