1

I'm having trouble with the following exercise :

I'm supposed to reverse all elements in a list except for the first one, the first element of the list must stay in its original position.

Correct Example:

input: rvrsTail [1,2,3,4,5]
output [1,5,4,3,2]

What I have done so far:

rvrsTail :: [x] -> [x]
rvrsTail xs = reverse ( tail xs)

This does reverse the the tail of the list but removes the first element, and since I can't store the first element in a variable I can't seem to understand how to solve this issue.

Erroneous Output:

input: rvrsTail [1,2,3,4,5]
output [5,4,3,2]

Since this is supposed to be a beginner's exercise, the solution should be simple.

recursion.ninja
  • 5,377
  • 7
  • 46
  • 78
eXistanCe
  • 735
  • 1
  • 9
  • 25

2 Answers2

5

When you receive a non-empty list, you must leave the head where it is and append the tail reversed. In other words, you can deconstruct the list into the head and the tail, then reconstruct the list with that head and the reversed tail:

rvrsTail :: [x] -> [x]
rvrsTail [] = []
rvrsTail (listHead : listTail) = listHead : reverse listTail
mariop
  • 3,195
  • 1
  • 19
  • 29
4

You are almost there. For making sure that the first element of the list stays as it is, just use pattern matching and remove the tail call:

rvrsTail :: [x] -> [x]
rvrsTail (x:xs) = x:(reverse xs)

Now, note that the above function will throw an exception when tried with empty list. You should handle that case.

Sibi
  • 47,472
  • 16
  • 95
  • 163
  • So i should implement some guards to handle the exception right? But if i do that, how can i specify that the return can be either a list ( if its not empty) or a String (to tell the string is empty in case it is) ? – eXistanCe Jul 24 '15 at 13:13
  • @nunocart Just think what output you want for an empty list input ? It need not be necessarily `String`. – Sibi Jul 24 '15 at 13:17