誰もが知っていShow
ます。しかし、どうですか:
class ShowText a where
showText :: a -> Text
これはどこにも見つかりません。なんで?
テキストを直接作成する場合の問題は、テキストを入力する前に、厳密なテキストブロックの全体的なサイズを知る必要があることです。BuilderスキームとData.Text.Lazyを使用すると、より適切に処理できます。Dan Doelはこれをbytestring-showで行いますが、Textに相当するものを私は知りません。
ライブラリのテキストショーが現在存在し、この問題を正確に解決します。
更新(2016年2月12日)
basic-preludeライブラリで提供されるshow
関数も、テキストに直接レンダリングします。
show :: Show a => a -> Text
basic-prelude
また、依存関係は。よりも少なくなりtext-show
ます。を使用する場合basic-prelude
は、ソースファイルの先頭に以下を追加して、コンパイルの問題を回避してください。
{-# LANGUAGE NoImplicitPrelude #-}
値の特定のケースについて、中間段階で使用せずに厳密な値Int
に変換するコードは次のとおりです。Text
Strings
import Data.Text
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy.Builder.Int (decimal)
showIntegral :: Integral a => a -> T.Text
showIntegral = toStrict. toLazyText . decimal
モジュールData.Text.Lazy.Builder.RealFloat
は、浮動小数点値に対して同様の機能を提供します。
Show
これらを使用して、タイプクラスの独自のバージョンを定義できます。
import Data.Text
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy.Builder.Int (decimal)
import Data.Text.Lazy.Builder.RealFloat (realFloat)
class ShowText a where
showText :: a -> Text
instance ShowText Int where
showText = toStrict . toLazyText . decimal
instance ShowText Float where
showText = toStrict . toLazyText . realFloat
次に、インスタンスの追加を開始できます(たとえば、タプル用のインスタンスが役立ちます)。
ピギーバックする独自の関数を作成するのは簡単Show
です。
showText :: Show a => a -> Text
showText = pack . show
ベーシックプレリュードとクラッシープレリュードの両方に機能が追加されましたtshow
。
tshow :: Show a => a -> Text
標準のプレリュードを使用している場合は、text-showライブラリを試してください。