Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

turning Strings into Text in Haskell

Tags:

io

haskell

d3.js

Using the Haskell d3.js library I am trying to make a bar chart a bar chart.

 import Control.Monad
 import qualified Data.Text as T
 import D3JS

 test :: Int -> IO ()
 test n = T.writeFile "generated.js" $ reify (box "#div1" (300,300) >>= bars n 300 (Data1D [100,20,80,60,120]))

Even with this simple example I have a number of questions.

  • import qualified seems to require namespaces. Then instead of Data.Text.writeFile we can write T.writeFile
  • Data.Text.writeFile does not appear listed in hackage's entry on Data.Text but I did find it in relation to prelude.

Here is an example of a simple T.writeFile error:

> import qualified Data.Text.IO as T
> T.writeFile "helloWorld.txt" "Hello World!"

Couldn't match expected type ‘Text’ with actual type ‘String’

Hopefully all of this type-casting can be sorted out. Then I have big question about how reify works. For now... how do I even changed the String to a Text here?

like image 361
john mangual Avatar asked May 15 '16 19:05

john mangual


People also ask

How do you define a String in Haskell?

In Haskell a String is just a list of Char s, indeed type String = [Char] . String is just an "alias" for such list. So all functions you define on lists work on strings, given the elements of that list are Char s.

What is text Haskell?

text: An efficient packed Unicode text type. The Text type provides character-encoding, type-safe case conversion via whole-string case conversion functions (see Data. Text). It also provides a range of functions for converting Text values to and from ByteStrings , using several standard encodings (see Data. Text.

What is show in Haskell?

The shows functions return a function that prepends the output String to an existing String . This allows constant-time concatenation of results using function composition.


2 Answers

Use Data.Text.pack to convert a String into Text:

pack :: String -> Text

Also, the Text version of writeFile appears in Data.Text.IO, e.g.:

import qualified Data.Text.IO as T

T.writeFile "helloWorld.txt" (T.pack "Hello World!")

It's ok to import both Data.Text and Data.Text.IO as T.

like image 139
ErikR Avatar answered Oct 29 '22 17:10

ErikR


In addition to the conversion functions mentioned, you might want to use the {-# LANGUAGE OverloadedStrings #-} pragma at the top of your file to enable tho OverloadedStrings extension, which lets you write string literals, but automatically converting them to a compatible type (say Text).

Read more at https://ocharles.org.uk/blog/posts/2014-12-17-overloaded-strings.html.

like image 25
ron Avatar answered Oct 29 '22 18:10

ron