Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in Haskell

Tags:

string

haskell

I want to write the code that will output :

length [1,2,3] => 3   

In Ruby, I could do it like :

puts "length [1,2,3] => #{[1,2,3].length}"

Following try is Haskell failed...

Prelude Data.List> print "length [1,2,3]"
"length [1,2,3]"
Prelude Data.List> print (length [1,2,3])
3
Prelude Data.List> print "length [1,2,3]" (length [1,2,3])

<interactive>:1:0:
  Couldn't match expected type `Int -> t'
     against inferred type `IO ()'
 In the expression: print "length [1,2,3]" (length [1, 2, 3])
 In the definition of `it':
      it = print "length [1,2,3]" (length [1, 2, 3])
 Prelude Data.List>
like image 858
pierrotlefou Avatar asked Aug 12 '09 07:08

pierrotlefou


4 Answers

You can also just use Text.Printf which is included in the GHC base libraries:

> let format s = printf "length %s => %d\n" (show s) (length s)
> format [1,2,3]
length [1,2,3] => 3

There are several string interpolation packages on Hackage http://hackage.haskell.org if you want fancier situations.

like image 137
Don Stewart Avatar answered Oct 21 '22 04:10

Don Stewart


While the other posters here mention many of the 'right' ways to do string interpolation, there is a fancier way using quasiquotation and the interpolatedstring-perl6 library:

{-# LANGUAGE QuasiQuotes, ExtendedDefaultRules #-}

import Text.InterpolatedString.Perl6 (qq)

main = putStrLn [$qq| length [1,2,3] => ${length [1,2,3]} |]

In fact there is also an interpolatedstring-qq library which offers a Ruby syntax.

{-# LANGUAGE QuasiQuotes, ExtendedDefaultRules #-}

import Text.InterpolatedString.QQ (istr)

main = putStrLn [$istr| length [1,2,3] => #{length [1,2,3]} |]

That said, you probably should just use show and ++ or concat to glue together the strings

main = putStrLn $ "length [1,2,3] => " ++ show (length [1,2,3])

or

main = putStrLn $ concat ["length [1,2,3] => ", show $ length (1,2,3)]

The latter tends to look nicer, code-wise, when you are gluing together a lot of string fragments.

like image 31
Edward Kmett Avatar answered Oct 21 '22 04:10

Edward Kmett


Strings are really just lists. So you can convert the number returned from length and append it to your other string with normal list functions:

print $ "length [1,2,3] " ++ show (length [1,2,3])
like image 23
CiscoIPPhone Avatar answered Oct 21 '22 05:10

CiscoIPPhone


Use format function from text-format-simple library:

import Text.Format
format "length [1,2,3] => {0}" [show $ length [1,2,3]]
like image 44
Dmitry Bespalov Avatar answered Oct 21 '22 05:10

Dmitry Bespalov