Char是Haskell中Unicode字符的类型,String简单来说[Char](即Char项目列表).这是一些简单的代码:
main = putStrLn "©" -- Unicode string
Run Code Online (Sandbox Code Playgroud)
这段代码编译得很好,但是当我在PowerShel.exe或cmd.exe中运行它时,我得到了运行时异常:
app.exe :: commitBuffer:无效参数(无效字符)
为什么会这样?奇怪的是,当我在C#中做同样的事情时,我也不例外:
Console.WriteLine("©");
Run Code Online (Sandbox Code Playgroud)
在.NET中,字符也是Unicode.相反,PowerShell或cmd打印,但至少我不会例外.如何让Haskell可执行文件顺利运行?c©
我认为这应该算作GHC中的一个错误,但有一个解决方法.GHC程序中所有句柄的默认编码(在二进制模式下打开的除外)只是控制台接受的编码,没有错误处理.幸运的是,你可以添加这样的错误处理.
makeSafe h = do
ce' <- hGetEncoding h
case ce' of
Nothing -> return ()
Just ce -> mkTextEncoding ((takeWhile (/= '/') $ show ce) ++ "//TRANSLIT") >>=
hSetEncoding h
main = do
mapM_ makeSafe [stdout, stdin, stderr]
-- The rest of your main function.
Run Code Online (Sandbox Code Playgroud)