public
Last active

Placeholder

  • Download Gist
gistfile1.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.