从守卫 haskell 中的 do 语句返回值

returning a value from do statement in a guards haskell

我正在尝试查找字符串列表中的任何字符串是否已经使用了某个字母。如果是 - 选择下一个字母进行比较。如果没有 - return 这封信并更新初始列表。

查看我正在使用的列表:

check:: [String] -> Char -> Char
check s c 
    | any (elem c) s = check s (next c)
    | otherwise = do update s c 
                     return c

但是它给我一个错误:

Couldn't match type ‘[Char]’ with ‘Char’
Expected type: [String] -> [Char] -> Char
Actual type: [String] -> [Char] -> [Char]
In a stmt of a 'do' block: update s c

我的更新函数有以下声明:

update:: [String] -> Char -> [String]

守卫2个动作有没有正确的方法otherwise? 我需要 return c 才能在另一个递归函数中使用它,该函数将 Char c[=48= 作为参数] 并更新了 [String] s

当我有这个功能时 returning only c,没有更新列表,那里没有错误:

check:: [String] -> Char -> Char
check s c 
    | any (elem c) s = check s (next c)
    | otherwise = c

欢迎任何提示。

更新: 我的下一个函数是:

next :: Char -> Char
next 'Z' = 'A'
next c = chr (ord c + 1)

我试过更新:

update:: [String] -> Char -> [String]
update s c = s ++ [[c]]

问题是稍后,我需要使用 [String] 这是更新的结果,以及 Char c (检查结果) 到另一个函数。 这就是为什么在执行检查后,我需要 return 一个值,并用它更新列表。

Haskell 是一种函数式语言,因此您不能(不应该)考虑改变数据结构,函数应该 return 该数据结构的更新版本,以及任何其他您想要的需要。最常见的方法是 returning 一个你需要的值的元组。您可能正在寻找以下内容:

check:: [String] -> Char -> (Char, [String])
check s c 
    | any (elem c) s = check s (next c)
    | otherwise = (c, s ++ [[c]])

通过这种方式您可以获得 "this" 字母和 String 初始列表的更新版本。