Skip to content

Instantly share code, notes, and snippets.

@corajr
Last active February 15, 2017 03:12
Show Gist options
  • Save corajr/1c803f864d386a374a2c87492e5f9b9e to your computer and use it in GitHub Desktop.
Save corajr/1c803f864d386a374a2c87492e5f9b9e to your computer and use it in GitHub Desktop.
Scrambler example
#!/usr/bin/env stack
-- stack --resolver lts-8.0 --install-ghc runghc --package hspec --package lens
import Test.Hspec
import Data.List (sort)
import Control.Lens (_init, _tail, (%~))
listScrambler :: String -> String
listScrambler = unwords . map f . words
where f (x:xs@(_:_)) = x:(sort (init xs)) ++ [last xs]
f xs = xs
lensScrambler :: String -> String
lensScrambler = unwords . map (_init . _tail %~ sort) . words
main :: IO ()
main = hspec spec
scramblerSpec :: String -> (String -> String) -> Spec
scramblerSpec name f =
describe name $ do
it "works on a single-letter word" $
f "a" `shouldBe` "a"
it "works on a two-letter word" $
f "an" `shouldBe` "an"
it "scrambles a word, leaving first and last letters untouched" $
f "zebra" `shouldBe` "zbera"
it "scrambles a sentence, leaving first and last letters in each word" $
f "The quick brown fox jumps" `shouldBe` "The qciuk borwn fox jmpus"
spec :: Spec
spec = do
scramblerSpec "listScrambler" listScrambler
scramblerSpec "lensScrambler" lensScrambler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment