HaskellのI/O - バイナリデータの操作 - Codec.Binary.UTF8.String, 文字数とバイト数
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT4(HaskellのI/O)、LESSON 25(バイナリデータの操作)、25.5(練習問題) Q25-1の解答を求めてみる。
コード
sample.hs
import qualified Data.Text as T
import Codec.Binary.UTF8.String
import System.Environment
import qualified Data.ByteString as B
main :: IO ()
main = do
args <- getArgs
let fileName = head args
contents <- B.readFile fileName
let (t, b) = lengths contents
putStrLn $ mconcat ["文字数: ", show t, ", バイト数: ", show b ]
lengths :: B.ByteString -> (Int, Int)
lengths bytes = (length (decode ( B.unpack bytes)), B.length bytes)
入出力結果(Terminal, Zsh)
% ghc -package-id text-2.0.2 sample.hs
Loaded package environment from /Users/.../.ghc/aarch64-darwin-9.4.8/environments/default
[1 of 2] Compiling Main ( sample.hs, sample.o ) [Source file changed]
[2 of 2] Linking sample [Objects changed]
ld: warning: ignoring duplicate libraries: '-lm'
% ./sample sample.hs
文字数: 440, バイト数: 454
%