我試圖創建自己的字符串隨機播放功能:類型錯誤
import System.Random
-- usage case: my_shuffle "something" ""
my_shuffle :: [Char] -> [Char] -> [Char]
my_shuffle [] result = result
my_shuffle s result = do
pos <- randomRIO (1, length s)
my_shuffle (remove_char pos) (result ++ (get_char pos))
get_char :: [Char] -> Int -> Char
get_char s pos = s !! (pos - 1)
remove_char :: [Char] -> Int -> [Char]
remove_char s pos = take (pos - 1) s ++ drop pos s
它返回的錯誤信息:
substitution_cipher.hs:8:16:
Couldn't match expected type `[t0]' with actual type `IO a0'
In the return type of a call of `randomRIO'
In a stmt of a 'do' expression: pos <- randomRIO (1, length s)
In the expression:
do { pos <- randomRIO (1, length s);
my_shuffle (remove_char pos) (result ++ (get_char pos)) }
當我看到它關係到IO,但我不知道如何解決它。
如果你不確定一個類型,它往往是方便省略式簽名,將其加載到GHCI,並做了':T'使哈斯克爾告訴你的類型。然後,您可以將該類型簽名添加到源代碼中。 –