gpt4 book ai didi

F# Or-Tools Sat 求解器

转载 作者:行者123 更新时间:2023-12-05 09:35:53 26 4
gpt4 key购买 nike

我正在试验 F#,并希望在我使用 Or-Tools 的地方进行一些约束编程。我以前将该包与 Python 一起使用,但我无法让它与 F# 一起使用。

我遵循 C# 示例:https://developers.google.com/optimization/cp/cp_solver#c_5

但在尝试添加约束时出现错误: enter image description here

最佳答案

所以这有点烦人,但这就是在 C# 中从 F# 重载的消耗运算符的工作方式。

无法使用 != 的原因像这样是因为:

  1. 接线员 !=在 C# 中作为 LinearExpr 上的静态运算符重载(这很不寻常)类。
  2. 接线员 !=编译为 op_Inequality ,但是 op_Inequality在 F# 中是 <> , 不是 !=
  3. F# 已经定义了 <>作为接受满足 equality 的任何成员的通用运算符约束,LinearExpr
  4. 定义的运算符<>正确解析,并生成 bool , 这与 model.Add 不兼容因为它不期望 bool

解决方案是明确限定您对运算符(operator)的访问权限,如下所示:

LinearExpr.(<>) (x, y)

请注意,因为它在其定义中采用元组参数,所以您还必须对参数进行元组处理,并且不能像“普通”运算符那样使用它。

这是完整的 F# 解决方案,通过一些小的调整使其符合地道:

#r "nuget: Google.OrTools"

open Google.OrTools.Sat

let model = CpModel()

// Creates the variables.
let num_vals = 3L;

let x = model.NewIntVar(0L, num_vals - 1L, "x")
let y = model.NewIntVar(0L, num_vals - 1L, "y")
let z = model.NewIntVar(0L, num_vals - 1L, "z")

// Creates the constraints.
model.Add(LinearExpr.(<>) (x, y))

// Creates a solver and solves the model.
let solver = CpSolver();
let status = solver.Solve(model)

if status = CpSolverStatus.Optimal then
printfn $"x = {solver.Value(x)}"
printfn $"y = {solver.Value(y)}"
printfn $"z = {solver.Value(z)}"

在 F# 中使它变得更好的一种方法是定义一个映射到 LinearExpr 的运算符模块。运营商是这样的:

module LinearExprOperators =
let ( ^<> ) (x: LinearExpr) (y: LinearExpr) = LinearExpr.(<>) (x, y)
let ( ^= ) (x: LinearExpr) (y: LinearExpr) = LinearExpr.(=) (x, y)

然后您可以改用这些运算符。另一个烦恼是,似乎 +-*工作得很好,因为 F# 类型不会产生像 bool 这样的不同类型.

简而言之,在 F# 中使用这个特定的 API 有点烦人。

关于F# Or-Tools Sat 求解器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65532910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com