Haskell QuasiQuotes Text.RawString.QQ interpolation

628 Views Asked by At

How can I interpolate like this:

{-# LANGUAGE QuasiQuotes #-}
import Text.RawString.QQ

myText :: Text -> Text
myText myVariable = [r|line one
line two
line tree
${ myVariable }
line five|]

myText' :: Text
myText' = myText "line four"

${ myVariable } prints as a literal, not an interpolation, can I do something similar that to interpolate in this case?

2

There are 2 best solutions below

0
On

Quasi quoter r doesn't implement interpolation. It's only for raw strings. You need another quasi quoter.

Complete code:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}

import Data.Text (Text)
import Text.RawString.QQ (r)
import NeatInterpolation (text)

rQuote :: Text -> Text
rQuote myVariable = [r|line one
line two
line tree
${ myVariable }
line five|]

neatQuote :: Text -> Text
neatQuote myVariable = [text|line one
line two
line tree
$myVariable
line five|]

rText, neatText :: Text
rText    = rQuote    "line four"
neatText = neatQuote "line four"

In ghci:

*Main> import Data.Text.IO as TIO
*Main TIO> TIO.putStrLn rText
line one
line two
line tree
${ myVariable }
line five
*Main TIO> TIO.putStrLn neatText
line one
line two
line tree
line four
line five
0
On

The only way I achieved my objective was just by concatenating:

{-# LANGUAGE QuasiQuotes #-}
import Text.RawString.QQ

myText :: Text -> Text
myText myVariable = [r|line one
line two
line tree
|] <> myVariable <> [r|
line five|]

myText' :: Text
myText' = myText "line four"