Haskell SplitOneOf定义问题

时间:2018-01-20 15:36:54

标签: haskell

Hello Guys:D回来了另一个Haskell问题。因此,我正在为期末考试而练习,而且我正在从过去的考试中进行练习,如果我没有弄错的话,它基本上将功能分开,我希望创建一个功能,一旦检测到一个一个给定的字符列表将它们从另一个列表中删除,并返回一个字符串列表,从中分割出来。

到目前为止,我所拥有的并不多,因为它不起作用,这是

sep :: Eq a => [a] -> [a] -> [[a]]
sep _ [] = []
sep n xs
    | n `elem` xs = ... (I had stuff in here, didn't put for sake of it being easier to understand where I'm at trouble)
    | otherwise = error "Error"

我想要的结果是:

ghci> sep " \t\n" "As armas\te\tos barões\n   que"
    **> ["As","armas","e","os","barões","que"]

编辑:在测试了你给我的帮助之后,它给了我一个错误,这就是我所拥有的:

sep :: Eq a => [a] -> [a] -> [[a]]
sep _ [] = []
sep n (x:xs) 
    | x `elem` n = " " ++ sep n xs
    | otherwise  = x : sep n xs

它给了我以下错误:

Couldn't match type 'Char' with '[a]'
  Expected type: [[a]]
    Actual type: [Char]
  In the expression: " " ++ sep n xs

Couldn't match type '[a]' with 'Char'
  Expected type: [Char]
    Actual type: [[a]]
In the second argument of ´(++)´, namely ´sep n xs´

1 个答案:

答案 0 :(得分:2)

当我们比较列表时,或者在这种情况下我理解我们比较字符串,我们需要了解一些事项。我们无法检查[a]类型的某些内容是否是某种其他类型[a]的元素。我们可以比较它们,但我们永远不能通过强制整个列表来比较元素。

[a] `elem` [a] // makes no sense
 a  `elem` [a] // is what we are looking for.

清理字符串很简单,一种方法是用其他东西替换所有符合某种要求的元素。在这种情况下,我们可以用空格替换所有元素,我们可以在结果上应用前奏函数words

sep :: String -> String -> String
sep _ [] = []
sep s1 (s:ss) | s `elem` s1 = " " ++ sep s1 ss
              | otherwise   =   s : sep s1 ss

然后我们可以通过将它与一些高效的haskell函数绑定在一起来使它更具有一些性能。

sep2 :: String -> String -> [String]
sep2 s1 s2 = words $ map(\x -> if (x `elem` s1) then ' ' else x) s2