K
K
Kryptonit2021-09-13 18:40:59
Haskell
Kryptonit, 2021-09-13 18:40:59

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

Here is the code, but it does not work with the number of elements greater than 3.
I just started learning Haskell, please help me figure it out, preferably with comments on the code

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasily Demin, 2021-09-13
@Kryptonit

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]

You can also reduce the number of pattern matching:
mylast :: [a]->[a]
mylast (x:xs) = mylast xs ++ [x]
mylast [] = []

M
mlyamasov, 2021-09-13
@mlyamasov

This is the standard reverse function from Prelude. There are two implementation options here: https://hackage.haskell.org/package/base-4.15.0.0/...

W
wiz, 2021-09-15
@wiz

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 question

Ask a Question

731 491 924 answers to any question