Reputation: 13588
I have to find a few examples that show that the built in Haskell function "unlines" is not the exact reverse of "lines", i.e,
unlines.lines x != x
where x is a String containing newlines. I found one example for that:
"aa\nbb"
will become
"aa\nbb\n"
Does anyone know any other examples, that don't show the same flaw (i.e., unlines always appends a newline after the last line)?
To clearify: According to the automated tests, I already solved the assignment - I simply used the above three times. I'm just interested if there is any other, fundamentally different solution.
Upvotes: 3
Views: 1172
Reputation: 937
If you use quickcheck you can find a smaller one:
import Test.QuickCheck
main = quickCheck $ \x -> (unlines . lines) x == x
It will automatically shrink counterexamples, so it will typically only report the smallest one it finds which is "a"
.
We can change the property to test only strings ending with \n
:
import Test.QuickCheck
main = quickCheck $ \x0 -> let x = x0 ++ "\n" in (unlines . lines) x == x
I did not find any counterexamples.
You might also be interested in testing the other direction, (lines . unlines)
. Excluding cases where one of the strings contain a newline, this property holds.
Upvotes: 9