Reputation:
I need guidance to how to make a perfect reverse in my code of Haskell. My code:
input :: Int -> [Int]
input x = check_1 x
check_1 x = check_2 (case x of
0 -> []
x -> check_1 (x`div`10) ++ [x`mod`10])
check_2 x = reverse x
My output:
Prelude -> input 12345
Prelude -> [5,3,1,2,4]
How I want:
Prelude -> input 12345
Prelude -> [5,4,3,2,1]
Please assist me in calling the check_2 function is a better way to reverse the list. Thanks
Upvotes: 0
Views: 567
Reputation: 370112
The problem is that you're reversing the list after each added item, so it ends up a jumble. You want to reverse once after you've added all the items. You can achieve that by getting rid of check_2
and changing input
to:
input x = reverse $ check x
However a better solution in this case would be to not reverse at all, but creating the list in the right order in the first place: If you change
check_1 (x`div`10) ++ [x`mod`10])
to
x `mod` 10 : check_1 (x `div` 10)
it will not only be more efficient because you got rid of the ++
, but the list will also be in reversed order from the start.
Upvotes: 4