Answer the question
In order to leave comments, you need to log in
How to change the order of a list in Haskell?
mylast::[a]->[a]
mylast [] = error "no elem"
mylast [z] = [z]
mylast[z,y] = [y, z]
mylast [z, y, m] = [m,y,z]
mylast (z:y:m) = mylast m
Answer the question
In order to leave comments, you need to log in
error is redundant here, if you flip a list of zero elements, you get a list of zero elements. Your code doesn't work correctly because in the last line you reverse the tail of the list and the first two elements are lost.
We get:
mylast :: [a]->[a]
mylast [] = []
mylast [z] = [z]
mylast [z,y] = [y, z]
mylast [z, y, m] = [m,y,z]
mylast (z:y:m) = mylast m ++ [y,z]
mylast :: [a]->[a]
mylast (x:xs) = mylast xs ++ [x]
mylast [] = []
This is the standard reverse function from Prelude. There are two implementation options here: https://hackage.haskell.org/package/base-4.15.0.0/...
The order of the entire list is `Data.List.reverse`.
Swapping the first with the last elements (judging by the comment in the answer) is a completely different task.
To solve it, you need to break it down into simpler ones.
The last case in this code does not "swap first and last element" at all. But what should happen there?
Clearly not the same as the whole function as a whole. Pull it into a separate function and describe what exactly it should do.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question