Created
July 8, 2014 01:33
-
-
Save cheecheeo/fc08e812fc505aaeb9ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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