[Haskell-cafe] NewLines in string
Serge D. Mechveliani
mechvel at botik.ru
Sat Oct 4 10:57:39 EDT 2008
People,
Here is a certain naive question about string setting in a Haskell
program.
I have the functions
parseProgram :: String -> Program
apply :: Program -> Term -> Term -- interpreter,
and try to build the example modules for them as in the following
example:
----------------------------------------------------------------
module Main where
program = parseProgram
"
isOrdered nil -> true;
isOrdered (X:nil) -> true;
isOrdered (X:Y:Ys) ->
isOrd (X > Y) (isOrdered (Y:Ys));
isOrd true bo -> false;
isOrd false bo -> bo
"
main = let {data = ... :: Term; res = apply program data}
in
putStr $ concat ["data = ", shows data "\n",
"res = ", shows res "\n"]
----------------------------------------------------------------
-- that is set a string (an object program example),
parse it to a program, apply this program and print the result.
But in reality, the above string must be set like this:
(2)
"\
\ isOrdered nil -> true;\
\ isOrdered (X:nil) -> true;\
\ isOrdered (X:Y:Ys) -> \
\ isOrd (X > Y) (isOrdered (Y:Ys));\
\\
\ isOrd true bo -> false;\
\ isOrd false bo -> bo\
\"
-- because otherwise Haskell treats the NewLine characters in the above
string in an unneeded way.
But with (2), the program Main occurs hard to read.
One could try to improve this by using readFile. Form the file
data.txt --------------------------------
isOrdered nil -> true;
isOrdered (X:nil) -> true;
isOrdered (X:Y:Ys) ->
isOrd (X > Y) (isOrdered (Y:Ys));
isOrd true bo -> false;
isOrd false bo -> bo
-----------------------------------------
and combine readFile "data.txt", the `do' construct,
pearseProgram, apply, putStr.
But this needs adding one more file, and this also changes the
programming style in defining examples.
Now, what is the difference?
1. readFile reads string from file, with treating NewLine as needed.
2. The Haskell compiler reads the expression
parseProgram
"
isOrdered nil > true;
...
"
from the input Haskell program with treating NewLine in the string
in a different way.
I wonder: how to remove most of backslashes in the program (2) ?
Thank you in advance for your comments.
-----------------
Serge Mechveliani
mechvel at botik.ru
More information about the Haskell-Cafe
mailing list