How can I write multiline strings in Haskell?

后端 未结 6 840
南旧
南旧 2021-02-02 05:10

Let\'s say I have this string literal with line breaks:

file :: String
file = \"the first line\\nthe second line\\nthe third line\"

Is there an

6条回答
  •  孤城傲影
    2021-02-02 05:47

    Some time ago I released a library named "neat-interpolation" to solve the problem of multiline strings and interpolation using the QuasiQoutes extension. Its primary advantage over competitors is a smart management of whitespace, which takes care of interpolated multiline strings. Following is an example of how it works.

    Executing the following:

    {-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
    
    import NeatInterpolation (text)
    import qualified Data.Text.IO
    
    f :: Text -> Text -> Text
    f a b = 
      [text|
        function(){
          function(){
            $a
          }
          return $b
        }
      |]
    
    main = Data.Text.IO.putStrLn $ f "1" "2"
    

    will produce this (notice the reduced indentation compared to how it was declared):

    function(){
      function(){
        1
      }
      return 2
    }
    

    Now let's test it with multiline string parameters:

    main = Data.Text.IO.putStrLn $ f 
      "{\n  indented line\n  indented line\n}" 
      "{\n  indented line\n  indented line\n}" 
    

    We get

    function(){
      function(){
        {
          indented line
          indented line
        }
      }
      return {
        indented line
        indented line
      }
    }
    

    Notice how it neatly preserved the indentation levels of lines the variable placeholders were at. The standard interpolators would have messed all the whitespace and produced something like the following instead:

        function(){
          function(){
            {
      indented line
      indented line
    }
          }
          return {
      indented line
      indented line
    }
        }
    

提交回复
热议问题