Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@paulcc
Last active December 11, 2015 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulcc/4577526 to your computer and use it in GitHub Desktop.
Save paulcc/4577526 to your computer and use it in GitHub Desktop.
Placeholder
import Data.List (elemIndex)
tests :: (Int -> String -> String) -> [Bool]
tests wrap
= [ wrap 1 "" == ""
, wrap 1 "x" == "x"
, wrap 1 "xx" == "x\nx"
, wrap 1 "xxx" == "x\nx\nx"
, wrap 1 "x x" == "x\nx"
, wrap 2 "x x" == "x\nx"
, wrap 3 "x xxxx" == "x\nxxx\nx"
]
check = putStrLn
$ unlines
$ zipWith (\n t -> show n ++ " " ++ if t then "ok" else "not") [1..]
$ tests wrap
--------------------
wrap_1 n x = x
wrap_2 n x = x
--------------------
wrap_3 n x | length x > n = take n x ++ "\n" ++ drop n x
| otherwise = x
--------------------
wrap_4 n x | length x > n = take n x ++ "\n" ++ wrap_4 n (drop n x)
| otherwise = x
--------------------
-- painful bit here
--
-- eg abc def x| -> ("x", " fed cba")
-- eg abcdefx| -> ("xfedcba", "")
-- x, ' ' ....
-- what about size zero? or negative? - but 0 is infinite....
wrap_5a n (' ':x) = wrap_5a n x
wrap_5a n x | null rest = line
| otherwise = reverse tail ++ "\n" ++ wrap_5a n (reverse head ++ rest)
where (line,rest) = splitAt n x
(tail, head) = break (== ' ') $ reverse line
-- 5a probably not enough to distinguish "x x x "
-- blows on wrap_5 3 "x x x "
-- 5b does it ok
-- maybe try refactoring?
-- poss this is 5a with the null case inlined?
-- benefits of equational reasoning
wrap_5b n x | null rest = line
| head rest == ' ' = line ++ "\n" ++ wrap_5b n (tail rest)
| null before = line ++ "\n" ++ wrap_5b n rest
| null after = reverse (drop 1 before) ++ "\n" ++ wrap_5b n rest
| otherwise = reverse before ++ "\n" ++ wrap_5b n (reverse after ++ rest)
where (line,rest) = splitAt n x
(after, before) = break (== ' ') $ reverse line
--------------------
wrap_6 n (' ':x) = wrap_6 n x
wrap_6 n x | null rest = line
| null tail = reverse (drop 1 head) ++ "\n" ++ wrap_6 n rest
| otherwise = reverse tail ++ "\n" ++ wrap_6 n (reverse head ++ rest)
where (line,rest) = splitAt n x
(tail, head) = break (== ' ') $ reverse line
-- 5b not on 2 "x x"
-- problem on << wrap 3 "x xxxx" >>
--------------------
-- wrap 3 "x xxxx" - bad
wrap_7 n "" = ""
wrap_7 n (' ':x) = wrap_7 n x
wrap_7 n x | null rest = line
| otherwise = case break (== ' ') $ reverse line of
(tail, []) -> reverse tail ++ "\n" ++ wrap_7 n rest
(tail, ' ':head) -> reverse head ++ "\n" ++ wrap_7 n (reverse tail ++ rest)
-- ([], head) -> reverse head ++ "\n" ++ wrap_7 n rest
where (line,rest) = splitAt n x
-- 5b not on 2 "x x"
wrap = wrap_7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment