Haskell:
Interpolating a string
How to:
In Haskell, string interpolation isn’t baked in, but with the interpolate
package, you can get pretty close. First, ensure you have the package:
cabal update
cabal install interpolate
Now, write some Haskell:
{-# LANGUAGE QuasiQuotes #-}
import Data.String.Interpolate (i)
main :: IO ()
main = do
let name = "world"
let greeting = [i|Hello, #{name}!|]
putStrLn greeting
Run it:
Hello, world!
Deep Dive
Historically, Haskell didn’t come with string interpolation out of the box. It’s a feature more common in scripting languages. Interpolation in Haskell became smoother with the development of quasiquoters, which allow you to define your own custom syntax—like our i
for interpolating strings.
Alternatives? Sure, use printf
from Text.Printf
, or concatenate strings and variables with ++
. But these lack the elegance and simplicity of interpolation.
Implementation-wise, interpolate
transforms your interpolated strings into regular Haskell strings at compile-time using Template Haskell, so there’s no performance hit when running your code. It’s clever and clean, just like Haskell.
See Also
- Hackage - interpolate package
- Hackage - Text.Printf module
- Haskell Wiki - Quasiquotation
- For rich templating, check out Hackage - Mustache templates