[英]Put string in to list in Haskell
我需要創建自己的文字功能。 它接受字符串並將其放到有空間的列表中。 例如,字符串“ i need help”將導致[“ i”,“ need”,“ help”]。 定義必須完全相同
anything :: String -> [String]
我目前想出了一個愚蠢的解決方案,看起來像這樣(也是行不通的)
test :: String -> [String]
test d = beforep d : (test (afterp d)) : []
beforep :: String -> String
beforep d = takeWhile (/=' ') d
afterp :: String -> String
afterp d = if (dropWhile (/=' ') d)==[] then []
else tail(dropWhile (/=' ') d)
測試->使用尾遞歸
事前准備->將所有東西放到第一位
afterp->在空格之后獲取所有內容
有任何想法嗎 ? 如果您對此問題有其他解決方案,則將有所幫助。 謝謝
您已經快知道了。 如果我嘗試按原樣運行您的代碼,則會得到:
test.hs:2:23:
Couldn't match expected type `Char' with actual type `String'
Expected type: String
Actual type: [String]
In the return type of a call of `test'
In the first argument of `(:)', namely `(test (afterp d))'
因此,請檢查第2行:
test d = beforep d : (test (afterp d)) : []
-- ^
-- This is the problem -----------------|
cons運算符的類型為:
(:) :: a -> [a] -> [a]
您的test
函數已經返回了[String]
,您不想嘗試將其限制在一個空列表中。 這意味着返回類型為[[String]]
。
嘗試以下方法:
test d = beforep d : (test (afterp d))
更改之后,它會編譯,但是當您運行test "i need help"
您將獲得無限列表:
["i","need","help","","","","","","","",""...
問題是您需要在test
中包括一個基本案例,當您將其傳遞給空列表時,該案例將停止。 這是工作代碼:
test :: String -> [String]
test [] = []
test d = beforep d : (test (afterp d))
beforep :: String -> String
beforep d = takeWhile (/=' ') d
afterp :: String -> String
afterp d = if (dropWhile (/=' ') d)==[] -- Slightly reformatted
then [] -- to improve readability,
else tail(dropWhile (/=' ') d) -- no real change.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.