我正在尝试创建一个函数拆分,该拆分可以采用[Int]和Int 或 [Char] Char来拆分给定整数上的整数列表或拆分字符上的字符串给定的。即
Main> split [1,2,3,4,5,7,8,9] 0
[[1,3],[4,5],[7,9]]
Main> split "Mary had a little lamb" ' '
["Mary","had","a","little","lamb"]
我尝试使用Either和(Eq a),但它似乎仍然不起作用。以下是我尝试使用类实例进行的操作,但对此我知之甚少,并收到错误Haskell 98 does not support multiple parameter classes
。
我认为我理解的最好方法是使用模式匹配或列表理解。任何帮助表示赞赏。
class Split a where
split :: (Eq a) => [a] -> a -> [a]
instance Split [Char] Char where
split [] c = [""]
split (x:xs) c
| x == c = "" : (split xs c)
| otherwise = (x : head (split xs c)) : tail (split xs c)
instance Split [Int] Int where
split [] n = []
split (x:xs) n
| x == n = [] : (split xs n)
| otherwise = (x : head (split xs n)) : tail (split xs n)
我可以使用split函数来处理字符串和字符,但不能处理整数列表。