創建一個函式,該函式接受一個字串并將其拆分為型別為 的元組串列
(word, length word)。它需要foldr通過串列的一次傳遞來完成 ,而不使用length和/或( )。例如
> splitSen " Asdf qw zx mn " [("Asdf",4),("qw",2),("zx",2),("mn",2)]
我的實作看起來像這樣
splitSen :: String -> [(String,Int)]
splitSen cs = foldr func [] cs where
func ' ' ((c1,n1) : ps) = ps
func c ((c1,n1) : ps) = (c:c1,1 n1):ps
我得到一個錯誤
*** 例外:函式 func 中的非窮盡模式
但無法弄清楚我缺少什么模式。
uj5u.com熱心網友回復:
讓我們打開警告!這可以通過-Wall標志來完成。
$ ghci -Wall
> :{
| splitSen :: String -> [(String,Int)]
| splitSen cs = foldr func [] cs where
| func ' ' ((c1,n1) : ps) = ps
| func c ((c1,n1) : ps) = (c:c1,1 n1):ps
| :}
<interactive>:6:3: warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘func’:
Patterns not matched:
p [] where p is not one of {' '}
' ' []
<interactive>:6:14: warning: [-Wunused-matches]
Defined but not used: ‘c1’
<interactive>:6:17: warning: [-Wunused-matches]
Defined but not used: ‘n1’
上面的警告告訴我們[]沒有處理空串列的情況func。
uj5u.com熱心網友回復:
如果有人在這里有類似的東西,我設法做到了
splitSen = fst . foldr func ([], True) where
func ' ' ([], _) = ([], True)
func c ([],bool) | bool = ([([c],1)], False)
func ' ' (((word, len):rest), bool) = (((word, len):rest), True)
func c (y@((word, len):rest), bool) | bool = (([c],1):y, False)
| otherwise = (((c:word, 1 len):rest), False)
看起來很糟糕,但有效...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363860.html
上一篇:Haskell決議器分隔符
