【发布时间】: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