Personal tools

Poor man's here document

From HaskellWiki

Revision as of 05:20, 20 April 2007 by Nedervold (Talk | contribs)

Jump to: navigation, search

1 Poor man's heredoc / here document

main = do
  doc <- here "DATA" "Here.hs" [("variable","some"),("substitution","variables")]
  putStrLn doc
  html <- here "HTML" "Here.hs" [("code",doc)]
  putStrLn html
here tag file env = do
  txt <- readFile file
  let (_,_:rest) = span (/="{- "++tag++" START") (lines txt)
      (doc,_) = span (/="   "++tag++" END -}") rest
  return $ unlines $ map subst doc
    subst ('$':'(':cs) = case span (/=')') cs of 
      (var,')':cs) -> maybe ("$("++var++")") id (lookup var env) ++ subst cs
      _ -> '$':'(':subst cs
    subst (c:cs) = c:subst cs
    subst "" = ""
this is a poor man's here-document
with quotes ", and escapes \, 
and line-breaks, and layout
without escaping \" \\ \n,
without concatenation.
oh, and with $(variable) $(substitution), $(too).
   DATA END -}
<head><title>very important page</title></head>
   HTML END -}

2 Even poorer man's here-doc / here-document

If you're just looking to define a multiline string constant, you can just say:

str :: String
str = unlines [
    "Here's a multiline string constant.",
    "\tIt's not as convenient as Perl's here-documents,",
    "\tbut it does the trick for me."

You can fake interpolation with:

hereDocPraise :: String -> String
hereDocPraise lang = unlines [
    "The language with the best here-document support",
    "in my opinion is " ++ lang ++ "."

Disadvantages to poorer man's here-docs:

  • You still need to escape special characters.
  • It ends with a newline whether you want one or not.

See Also