Skip to content

Instantly share code, notes, and snippets.

@cheecheeo
Created July 8, 2014 01:33
Show Gist options
  • Save cheecheeo/fc08e812fc505aaeb9ca to your computer and use it in GitHub Desktop.
Save cheecheeo/fc08e812fc505aaeb9ca to your computer and use it in GitHub Desktop.
module Roll where
{--
Okay, shoot! Fell asleep while composing a problem; sorry for the delay!
So, this one is an easy one. We get a little Forth'y'. This is from P19
of the P99 problem-set.
--}
-- | Roll a list @n@ elements to the left
-- >>> roll [1,2,3] 1
-- [2,3,1]
-- >>> roll [1,2,3] 2
-- [3,1,2]
-- >>> roll [1,2,3] (-1)
-- [3,1,2]
-- >>> roll [1,2,3] (-2)
-- [2,3,1]
-- >>> roll [1,2,3] 9
-- [1,2,3]
-- >>> roll [1,2,3] 8
-- [3,1,2]
roll :: [a] -> Int -> [a]
roll list n =
let (hd, tl) = splitAt realN list
len = length list
realN = (if signum n < 0 then len + n else n) `mod` len
in tl ++ hd
{--
roll rotates list n steps to the left.
roll [1,2,3] 1 ~> [2,3,1]
The argument n can be negative, indicating that the rotation is to occur
to the right, then, instead.
roll [1,2,3] (-1) ~> [3,1,2]
(Recall that we write '(-1)' and not just '-1' because '-1' is interpreted
as the binary operator (-) applied to the Int 1)
The list can be rotated multiple times, so:
roll [1,2,3] 9 ~> [1,2,3]
Have at it!
Explanation: the term ROLL comes from the FORTH programming language,
placing the n-th element of the stack on TOS ('top of stack').
--}
-- A solution is provided at http://lpaste.net/107063
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment