简体   繁体   中英

How do I putStrLn a Data.ByteString.Lazy.Internal.ByteString?

I use encode (Haskell type via JSON to a string):

import GHC.Generics
import Data.Aeson

The string is (according to an error message from the compiler): Data.ByteString.Lazy.Internal.ByteString .

How do I putStrLn it?

put theoretically

What I'm in search for is a an ad-hoc polymorphic putStrLn , ie, I'm looking for the proper instance of putStrLn semantics for a specific string-like type.

compiler messages

The compiler message if someone is interested:

valencies.lhs:182:22:
    Couldn't match type `Data.ByteString.Lazy.Internal.ByteString'
                  with `[Char]'
    Expected type: String
      Actual type: Data.ByteString.Lazy.Internal.ByteString
    In the return type of a call of `encode'
    In the first argument of `putStrLn', namely `(encode CALL)'
    In the expression: putStrLn (encode CALL)

see also

Similar question, but with a bit different type: How do I putStrLn a Data.ByteString.Internal.ByteString? .

This really depends on your ByteString . Does it really contain printable characters? What's the encoding on it? You can use toString from utf8-string if you know it contains valid UTF-8 and then pass it to putStrLn .

By the way, Hayoo is great for this type (hehe) of questions. Put a type in there and it will get you functions from Hackage with those types!

You may use string-class package, it has three options: toString function (defaults to utf-8), fromLazyByteString function, and putStrLn that works with all the types. Note, that you need to do:

import Prelude hiding (putStrLn)
import Data.String.Class (putStrLn)

In this case, we have a Lazy variant, so we must use Data.ByteString.Lazy.putStrLn .

Note that the compiler gives an interesting warning:

In the use of `Data.ByteString.Lazy.putStrLn'
(imported from Data.ByteString.Lazy):
Deprecated: "Use Data.ByteString.Lazy.Char8.putStrLn instead. (Functions that rely on ASCII encodings belong in Data.ByteString.Lazy.Char8)"

Probably, if I want UTF-8 encoded strings, I should use another variant rather than the recommended Char8 one. I'll try to find out this.

smart string-class

For a smart way, also have a look at string-class package mentioned in another answer by Konstantine Rybnikov .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM