【发布时间】:2014-02-12 02:54:25
【问题描述】:
我正在尝试根据最长的公共前缀 cpfx 匹配文件,并且对 haskell 有点陌生。我正在尝试获取列表列表并简单地返回它们共享的前缀。例如:
cpfx ["obscure","obscures","obscured","obscuring"] --> "obscur"
cpfx ["abc", "ab", "abcd"] --> "ab"
我正在尝试使用几个辅助方法,如下所示:
cpfx :: [[Char]] -> [Char]
cpfx [] = [] -- nothing, duh
cpfx (x:[]) = x -- only one thing to test, return it
cpfx (x:t) = cpfx' (x:t) 0 -- otherwise, need to test
cpfx' (x:[]) _ = []
cpfx' (x:t) n
-- call ifMatch to see if every list matches at that location, then check the next one
| ifMatch (x:t) n = x!!n + cpfx' x (n+1)
| otherwise = []
-- ifMatch means if all words match at that location in the list
ifMatch (x:[]) _ = True
ifMatch (x:xs:[]) n = x!!n == xs!!n
ifMatch (x:xs:t) n
| x!!n == x!!n = ifMatch xs n
| otherwise = False
但我收到错误消息:
Occurs check: cannot construct the infinite type: a0 = [a0]
我猜这与ifMatch (x:t) n = x!!n + cpfx' x (n+1) 行有关。
我能做些什么来补救这种情况?
【问题讨论】:
-
离题:
cpfx [] = [] -- nothing, duh并不是那么“废话”。空[[a]]的公共前缀是未定义的,即公共前缀可以是anything,因为没有任何东西可以作为前缀进行测试。