【问题标题】:F# recursion with boolean value带有布尔值的 F# 递归
【发布时间】:2013-10-08 14:24:29
【问题描述】:

所以这是上下文。假设我有一个函数需要 2 个实验的元组并根据规则列表对其进行测试。只要实验的元组被某个规则正确验证,该函数就应该停止。

type exp = A | B | Mix of exp * exp | Var of string

type sufficency = exp * exp  

type rule = Rule of sufficency * (sufficency list) 


let rec findout rules (exp1, exp2) = // return a boolean value
            match rules with
            | [] -> true
            | thisRule::remaining ->
                match thisRule with
                | (suff, condition) ->
                    match suff with
                    | (fstExp, sndExp) ->
                        let map1 = unify Map.empty exp1 fstExp // I don't mention this function in here, but it is defined in my code
                        let map2 = unify Map.empty exp2 sndExp
                        true
                findout remaining (exp1, exp2)

问题是,我不知道如何使用这样的函数式编程来完成。使用命令式编程,循环遍历规则列表会更容易,而不是使用递归遍历列表。

那么函数在递归的每个阶段应该返回什么?

我收到了上面代码的警告

警告 FS0020:此表达式应具有类型“单元”,但具有类型 '布尔'。使用 'ignore' 丢弃表达式的结果,或使用 'let' 将结果绑定到名称。

【问题讨论】:

  • 您的unify 代码丢失。另外,functional <> recursive。随意使用List.tryFind 和朋友。
  • 嗨,John,我没有在帖子中提到 unify 函数,但它已在我的代码中定义。
  • 您可以一次解构列表的整个头部,而不是多个单案例匹配语句:| ((fstExp, sndExp), condition) :: remaining ->。此外,空列表的情况看起来应该返回 false,否则 findout 将始终返回 true。

标签: recursion f# functional-programming


【解决方案1】:

所以问题出在这部分代码

            match thisRule with
            | (suff, condition) ->
                match suff with
                | (fstExp, sndExp) ->
                    let map1 = unify Map.empty exp1 fstExp // I don't mention this function in here, but it is defined in my code
                    let map2 = unify Map.empty exp2 sndExp
                    true
            findout remaining (exp1, exp2)

第一个 match 返回 true,因此您会收到警告。你可能想要

            match thisRule with
            | (suff, condition) ->
                match suff with
                | (fstExp, sndExp) ->
                    let map1 = unify Map.empty exp1 fstExp // I don't mention this function in here, but it is defined in my code
                    let map2 = unify Map.empty exp2 sndExp
                    true && findout remaining (exp1, exp2)

您在哪里通过计算携带true。但是,如果您使用各种 List.* 函数,这可能会更简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2020-08-02
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多