List 接受两个字符串并根据第一个字符串过滤第二个字符串的Haskell函数
目标是:使用List 接受两个字符串并根据第一个字符串过滤第二个字符串的Haskell函数,list,haskell,filter,List,Haskell,Filter,目标是:使用foldr,定义一个函数remove,该函数以两个字符串作为参数,并从第一个列表中出现的第二个列表中删除每个字母。例如,删除“第一个”“第二个”=“第二个” 如果此函数使用单个字符和字符串,我将执行以下操作: remove a xs = foldr (\x acc -> if x /= a then x : acc else acc) [] xs 但我不知道我应该如何用两条线来做这件事。谢谢大家! remove xs ys = foldr (\x acc -> if e
foldr
,定义一个函数remove,该函数以两个字符串作为参数,并从第一个列表中出现的第二个列表中删除每个字母。例如,删除“第一个”“第二个”=“第二个”
如果此函数使用单个字符和字符串,我将执行以下操作:
remove a xs = foldr (\x acc -> if x /= a then x : acc else acc) [] xs
但我不知道我应该如何用两条线来做这件事。谢谢大家!
remove xs ys = foldr (\x acc -> if elem x xs then acc else x : acc) [] ys
是的
还允许放弃“ys”参数输入:
remove :: String -> String -> String
remove xs = foldr (condCons) ""
where
condCons l rs | l `notElem` xs = l : rs
| otherwise = rs
基本上,condCons接受一个字符L和一个字符串Rs。如果L不是xs的元素,那么它将转换为Rs,否则保持Rs不变。foldr接受condCons、初始字符串“”和第二个参数ys。L从右到左接受字符串ys的每个字符,使用condCons二进制运算符从“”生成一个新字符串。提示:使用
elem
。我很笨。。。谢谢你@WillemVanOnsem
remove :: String -> String -> String
remove xs = foldr (condCons) ""
where
condCons l rs | l `notElem` xs = l : rs
| otherwise = rs