GHC(Haskell コンパイラ) 単体では日本語(マルチバイト文字)が使えません。単純に出力しようとすると文字化けしちゃいます><
なぜかというと、
http://ja.doukaku.org/comment/2957/ から引用
さらにghcでは文字は内部的にはUCS4で表現されているといってよいのですが,
エンコーディングを変換する機構が標準では提供されていません.
外部から文字列データを読み込み,それを逆転し,外部へ出力するためには
エンコーディングを変換する機構を自前で用意するか,それ用のライブラリ
モジュールを使う必要があります
そこで色んな対処方があるのですが、utf8-string という素敵なパッケージがありますので、これを使います。
環境
- GHC 6.8.2
- Ubuntu (UTF8 な OS なら何でも)
utf8-string をインストール
wget http://hackage.haskell.org/packages/archive/utf8-string/0.3.1/utf8-string-0.3.1.tar.gz
tar zxf utf8-string-0.3.1.tar.gz
cd utf8-string-0.3.1/
runhaskell Setup.lhs configure
runhaskell Setup.lhs build
sudo runhaskell Setup.lhs install
ちゃんとインストールできたか確認
ghc-pkg -l | grep utf8
unix-2.3.0.0, utf8-string-0.3.1, xhtml-3000.0.2.1
utf8-string が表示されればOK!
試してみる
以下のコードを test.hs に保存。
module Main where
import qualified System.IO.UTF8 as U
main = do
U.putStrLn "あいうえお"
コンパイル
ghc --make test.hs
実行
$ ./test
あいうえお
日本語きたーーー
System.IO.UTF8 が提供する他のメソッドについては以下の通り。他にもさっき落としたソースを読めば使えそうなメソッドがありそうな感じです。Codec.Binary.UTF8.String とか他にもいろんなモジュールがあるっぽい。
module System.IO.UTF8 (
print
, putStr
, putStrLn
, getLine
, readLn
, readFile
, writeFile
, appendFile
, getContents
, hGetLine
, hGetContents
, hPutStr
, hPutStrLn
) where
ちなみに今回みたいに外部パッケージを import したファイルをコンパイルする時には make オプションを付けないとリンクが作れないみたいな以下のようなエラーメッセージが出ます。
$ ghc test.hs
test.o: In function `siz_info':
(.text+0xaa): undefined reference to `utf8zmstringzm0zi3zi1_SystemziIOziUTF8_putStrLn_closure'
test.o: In function `siz_info':
(.text+0x14f): undefined reference to `__stginit_utf8zmstringzm0zi3zi1_SystemziIOziUTF8_'
test.o: In function `siz_closure':
(.data+0x14): undefined reference to `utf8zmstringzm0zi3zi1_SystemziIOziUTF8_putStrLn_closure'
collect2: ld はステータス 1 で終了しました
Recent Comments