如果字符串中存在一个字母,则给出一个字符
Give a char if a letter exists in a string
我目前在执行 letterCheck 函数时遇到问题,该函数在给定两个字符串的情况下给出一串数字。我的代码如下:
letterCheck :: String -> String -> String
letterCheck _ [] = []
letterCheck (w:ws) (y:ys)
| w == y = '3' : letterCheck ws ys
| w `elem` (y:ys) = '7' : letterCheck ws ys
| otherwise = '9' : letterCheck ws ys
参考我要的条件是:
If letter in string 1 is the same as a letter in string 2, give '3';
If letter in string 1 exists in string 2 but is not the same, give '7';
Otherwise if a letter in string 1 isn't in string 2 at all, give '9';
代码中的第二个守卫将不起作用,因为被引用的第二个字符串会递减,直到完整字符串中没有元素可供比较。我怎样才能解决这个问题?
如果您想要访问整个字符串,则必须传递未被解构的整个字符串的副本。您可以使用 where
块隐藏此实现细节:
letterCheck ws ys = go ws ys ys where
go _ [] _ = []
go (w:ws) (y:ys) ysAll
| w `elem` ysAll = '7' : letterCheck ws ys ysAll
我目前在执行 letterCheck 函数时遇到问题,该函数在给定两个字符串的情况下给出一串数字。我的代码如下:
letterCheck :: String -> String -> String
letterCheck _ [] = []
letterCheck (w:ws) (y:ys)
| w == y = '3' : letterCheck ws ys
| w `elem` (y:ys) = '7' : letterCheck ws ys
| otherwise = '9' : letterCheck ws ys
参考我要的条件是:
If letter in string 1 is the same as a letter in string 2, give '3';
If letter in string 1 exists in string 2 but is not the same, give '7';
Otherwise if a letter in string 1 isn't in string 2 at all, give '9';
代码中的第二个守卫将不起作用,因为被引用的第二个字符串会递减,直到完整字符串中没有元素可供比较。我怎样才能解决这个问题?
如果您想要访问整个字符串,则必须传递未被解构的整个字符串的副本。您可以使用 where
块隐藏此实现细节:
letterCheck ws ys = go ws ys ys where
go _ [] _ = []
go (w:ws) (y:ys) ysAll
| w `elem` ysAll = '7' : letterCheck ws ys ysAll