0
votes

I have the following problem:

We can cycle a list by a fixed amount by taking the given number of items off the front and adding them to the back of the list.
Write a function called rotor so rotor 6 "ABCDEFGHIJKLMN" produces "GHIJKLMNABCDEF". Give the type as well as the definition for
rotor. Make sure it returns an error message if the offset number is
less than 0 or bigger than or equal to the length of the list.

And the following Haskell code:

rotor :: (Ord a) => a -> [a] -> [a]
rotor a (x:xs) 
  | if a < 1  = error "Error"
  | a [] = a []
  | otherwise = rotor a-1 xs ++ [x]

but when I compile it I get the following error:

parse error on input "="

I don't understand what I'm doing wrong. Any ideas?

2
Your a-1 will need parentheses: (a-1). Also, it is often a good idea to leave off the type signature for a function and use the :type command to have ghci tell you what the signature should be. - ErikR
Read instructions carefully: The instruction says "number is less than 0", but the code reads < 1. Getting the edge cases right is important. BTW, I'd challenge that error requirement: As the word rotor suggests, negative values corresponds to counter-rotation, and there is a fine solution for rotating more than one revolution (length of the list). - Franky

2 Answers

3
votes
rotor :: (Ord a) => a -> [a] -> [a]
rotor a (x:xs) 

This line matches non-empty lists x:xs, only.

  | if a < 1  = error "Error"

No if is needed here.

  | a [] = a []

This should have been another pattern: after the | a boolean expression is expected.

An amended version of your code:

rotor :: (Ord a) => a -> [a] -> [a]
rotor a _      | a < 1 = error "Error"
rotor _ []             = []
rotor a (x:xs)         = rotor a-1 xs ++ [x]

This is not a correct solution, yet, since it does not satisfy your requirements, but it's a step in the right direction.

2
votes

if in line 3 is not necessary. Guard expressions don't need it.