テキストを高速に処理するtextパッケージ

 2011年2月中にリリースが予定されているHaskell Platform 2011.1.0.0では,HackageDBで提供されている「textパッケージが新しく追加される見込みです。

 textは,テキスト処理を高速に行うことを目的としたライブラリです。こう書くと,第2回で紹介したbytestringパッケージのByteStringを思い浮かべるかもしれません。

 textとByteStringの大きな違いは,ByteStringが1バイト=1文字の8ビット文字を利用することを想定しているのに対し,textはStringと同様にUnicode文字列を扱うことを目的としていることです。ByteStringは8ビット文字を想定しているため,処理によってはByteStringのほうが高速です。しかし,日本語などのUnicode文字列を含む処理には使えません。バイト単位での処理を効率的に行いたいならByteString,Unicode文字を含む文字列を効率的に扱いたいならtextを使うことになります。

 textパッケージで提供されているData.TextモジュールのText型は,ByteStringと同様に,pack関数やunpack関数を使うことでStringと相互変換できます。

Prelude Data.Text> :t pack
pack :: String -> Text
Prelude Data.Text> :t unpack
unpack :: Text -> String

 また,Data.Text.IOモジュールを使ってハンドル経由で文字を読み込んだり書き出したりすることもできます(Unicodeをハンドルで扱う方法は第39回のコラムを参照してください)。

Prelude Data.Text.IO> :browse
~ 略 ~
hGetContents ::
  GHC.IO.Handle.Types.Handle
  -> IO text-0.11.0.1:Data.Text.Internal.Text
~ 略 ~
hPutStrLn ::
  GHC.IO.Handle.Types.Handle
  -> text-0.11.0.1:Data.Text.Internal.Text
  -> IO ()
~ 略 ~
Data.Text.IO.readFile ::
  FilePath -> IO text-0.11.0.1:Data.Text.Internal.Text
Data.Text.IO.writeFile ::
  FilePath -> text-0.11.0.1:Data.Text.Internal.Text -> IO ()

 なお,textはTextとByteStringを相互変換する機能も提供しています。Data.Text.EncodingモジュールのencodeUtf*関数は,TextからUTF-*形式の文字列を格納したByteStringを作成します。逆にdecodeUtf*は,UTF-*形式の文字列を格納したByteStringからTextを作成します。

Prelude Data.Text.Encoding> :browse
~ 略 ~
decodeUtf16BE ::
  Data.ByteString.Internal.ByteString
  -> text-0.11.0.1:Data.Text.Internal.Text
~ 略 ~
decodeUtf32BE ::
  Data.ByteString.Internal.ByteString
  -> text-0.11.0.1:Data.Text.Internal.Text
~ 略 ~
decodeUtf8 ::
  Data.ByteString.Internal.ByteString
  -> text-0.11.0.1:Data.Text.Internal.Text
~ 略 ~
encodeUtf16BE ::
  text-0.11.0.1:Data.Text.Internal.Text
  -> Data.ByteString.Internal.ByteString
encodeUtf16LE ::
  text-0.11.0.1:Data.Text.Internal.Text
  -> Data.ByteString.Internal.ByteString
encodeUtf32BE ::
  text-0.11.0.1:Data.Text.Internal.Text
  -> Data.ByteString.Internal.ByteString
encodeUtf32LE ::
  text-0.11.0.1:Data.Text.Internal.Text
  -> Data.ByteString.Internal.ByteString
encodeUtf8 ::
  text-0.11.0.1:Data.Text.Internal.Text
  -> Data.ByteString.Internal.ByteString

 ほかにtextパッケージでは,Data.Listモジュールで提供されているtakeやdropなどのリスト処理関数のText対応版や,文字列の置換・切り分けといった文字列処理に必要な関数などが提供されています。

Prelude Data.Text> :t Data.Text.take
Data.Text.take :: Int -> Text -> Text
Prelude Data.Text> :t Data.Text.drop
Data.Text.drop :: Int -> Text -> Text
Prelude Data.Text> :t append
append :: Text -> Text -> Text

Prelude Data.Text> :t replace
replace :: Text -> Text -> Text -> Text
Prelude Data.Text> :t split
split :: (Char -> Bool) -> Text -> [Text]
Prelude Data.Text> :t splitOn
splitOn :: Text -> Text -> [Text]

著者紹介 shelarcy

 今回は,GHCで提供されている実行時情報の収集機能のうち,特別なオプションを使ったGHCのビルドが不要で,ボトルネックを探し出すのに有益な機能を紹介しました。GHCでは,ほかにも様々な実行時情報を収集できます(参考リンク1参考リンク2参考リンク3)。興味のある方はチェックしてみてください。