我正在做一些Haskell練習,但無法解決最後一個問題。從字符串中取出所有數字並將它們呈現在列表中
我需要遞歸定義已在Data.Char模塊中定義的函數。
最後一個函數我需要定義是這種類型的:
nums :: String -> [Int]
這裏是(翻譯)問題:
從Data.Char模塊使用的功能,定義遞歸以下函數:
(c)nums :: String - > [Int]它接收到一個字符串,並輸出一個列表 與該字符串上發生的algarisms,按相同的順序。
--This is my code
numbers :: String -> [Int]
numbers [] = []
numbers (l:ls) = if ord l >= 48 && ord l <= 57
then l : (numbers ls)
else (numbers ls)
我已經得到的解釋此錯誤:
pratica3.hs:137:14:
Couldn't match expected type `Int' with actual type `Char'
In the first argument of `(:)', namely `l'
In the expression: l : (numbers ls)
In the expression:
if ord l >= 48 && ord l <= 57 then
l : (numbers ls)
else
(numbers ls)
Failed, modules loaded: none.
謝謝。
你只是在進行過濾,但當你把它放在'數字ls'中時'l'仍然是一個'Char'。您需要將'l'轉換爲'Int'。 –
您可以直接比較「字符」,例如'l'='0'&& l <='9',沒有必要在那裏將它們轉換爲'Int'。在構建「Int」列表之前,您必須先轉換它們。此外,您的代碼僅會生成一位數字的列表。例如。它永遠不會包含123,只有1,2,3。這是打算嗎? – chi
可能是你想要將字符串分解爲'words',並通過'read'的某些實現將它們轉換爲數字('map')? – jakubdaniel