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>
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.
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.
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])
Use format function from text-format-simple library:
import Text.Format
format "length [1,2,3] => {0}" [show $ length [1,2,3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With