此表达式的结果具有 bool 类型,并且在 F# 中使用 if then else 时被隐式忽略

The result of this expression has type bool and is implicitly ignored when using if then else in F#

完整错误表示为“此表达式的结果被隐式忽略。考虑使用 'ignore' 例如 'expr |> ignore',或 ' 例如 'let result = expr'"

完全公开 -> 我是 F# 的新手,正在努力了解如何在适用的情况下将我的 OOP 知识转化为函数式编程。对于这个特定错误,我在 SO 上看到了另外 1 个 post,但它与我的场景没有直接关系。

module WebAPI =
let DoesSpecifiedHeaderExist(content: string[], searchString: string) = 
    if (content.Length > 0) then 
        for s in content do 
            if (s.Trim() = searchString.Trim()) then true else false
    else content |> ignore

代码要求并不复杂,因为我只是想遍历字符串数组以搜索 searchString 中提供的值。如果我找到匹配项,我 return 为真,否则 return 为假。我敢肯定还有其他方法可以做到这一点,但我真的很想了解这个问题。

错误发生在 if..then..else 块的循环中,但我不明白为什么会收到错误或如何更正代码。当我在条件上明确 return 为 true 或 false 时,表达式的结果如何被隐式忽略?我该如何更正它?

问题是 for 循环 returns 单元。所以

的类型
if (s.Trim() = searchString.Trim()) then true else false

bool

的类型
for s in content do 
    if (s.Trim() = searchString.Trim()) then true else false

unit

所以在 for 循环中你生成了一个 true/false 值然后什么也不做,结果永远不会跳出循环。

对于您在此代码中实际尝试执行的操作,您可能需要查看 List.tryFind。可能是这样的:

let DoesSpecifiedHeaderExist(content: string[], searchString: string) = 
    match (List.tryFind (fun v -> v = searchString) content) with
    | Some s -> true
    | None -> false

所以如果找到搜索字符串,请尝试查找 returns Some;否则它 returns None,匹配将结果转换为布尔值。另一种可能是

List.tryFind (fun v -> v = searchString) content |> Option.isSome

使用 Option.isSome 将选项转换为布尔值。