2012-06-12 38 views
1

就像標題所示,我在使用Haskell時打印符號代碼及其相應符號時遇到了一些麻煩......我現在所擁有的是:在Haskell中使用遞歸打印出符號代碼及其相應符號

import Data.Char 
import Debug.Trace 

foo z | trace ("Symbolcode " ++ show z ++ " is " ++ (chr z)) False = undefined 
foo z = if (z <= 128) 
    then foo (z+1) 
    else show "All done." 

...我得到這樣一個錯誤:

Couldn't match expected type `[Char]' with actual type `Char' 
In the return type of a call of `chr' 
In the second argument of `(++)', namely `(chr z)' 
In the second argument of `(++)', namely `" is " ++ (chr z)' 

什麼我做錯了,有沒有這樣做(例如不使用跟蹤模塊)的更簡單的方法?

+0

'main = putStrLn ['\ 128'..]''? –

回答

4

這是一個壞主意,用trace比其他調試任何東西,因爲the execution order is unreliable

如果您想對某個範圍內的所有整數執行某些操作,請首先將要處理的整數列表爲[0 .. 127]。要輸出一些文本,您應該使用IO操作,例如putStrLn。與trace不同,putStrLn將始終在應該執行時執行。 Map這個IO動作在你的列表上打印所有的字符。

showCharCode n = putStrLn ("Symbol code " ++ show n ++ " is " ++ [chr n]) 
foo = mapM_ showCharCode [0 .. 127] 
+0

它從來沒有打我,他不想調試該程序,但想用它來實際輸出! – dflemstr

5

您需要將Char轉換,如(通過[chr z]return (chr z)chr z : []等爲例)由chr z產生,爲String。否則,在使用++之前,不能將其附加到字符串。

foo z | trace ("Symbolcode " ++ show z ++ " is " ++ [chr z]) False = undefined 
+0

啊哈!非常感謝! –