algorithm - 在 F# 中创建(伪)循环可区分联合

标签 algorithm f#

我在这里遇到了一个小问题。我写了Tortoise and Hare cycle detection algorithm .

type Node = 
    | DataNode of int * Node
    | LastNode of int

let next node = 
    match node with 
    |DataNode(_,n) -> n 
    |LastNode(_) -> failwith "Error"

let findCycle(first) =
    try
      let rec fc slow fast =
          match (slow,fast) with
          | LastNode(a),LastNode(b) when a=b -> true
          | DataNode(_,a), DataNode(_,b) when a=b -> true
          | _ -> fc (next slow) (next <| next fast)
      fc first <| next first 
    with
    | _ -> false

这非常适合

  let first = DataNode(1, DataNode(2, DataNode(3, DataNode(4, LastNode(5)))))
  findCycle(first)

显示错误。正确的。现在,当尝试测试一个循环时,我无法创建循环!

显然这永远行不通:

  let first = DataNode(1, DataNode(2, DataNode(3, DataNode(4, first))))

但我需要那种东西!你能告诉我如何创建一个吗?

最佳答案

您不能对您定义的类型执行此操作。请参阅How to create a recursive data structure value in (functional) F#?一些可行的替代方法。

作为 Brian 解决方案的替代方案,您可以尝试以下方法:

type Node = 
| DataNode of int * NodeRec
| LastNode of int
and NodeRec = { node : Node }

let rec cycle = DataNode(1, { node = 
                DataNode(2, { node = 
                DataNode(3, { node = 
                DataNode(4, { node = cycle}) }) }) })

关于algorithm - 在 F# 中创建(伪)循环可区分联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4808955/

相关文章:

arrays - 给定两个大小相同的数组,从两个数组中找到使总和具有最小绝对值的元素对

algorithm - 为什么哈希表时间复杂度的最坏情况是O(n)

arrays - 如果我将序列转换为数组并将其视为序列,那么长度是否为 O(1)?

f# - 错误 F# - c# async 调用 : converting Threading. Tasks.Task<MyType> 到 Async<'a>

functional-programming - 在不使用嵌套 map 的情况下为列表列表实现 map 功能

f# - 如何确定两种类型之间的单一属性差异?

algorithm - 如何在类似推特的场景中计算趋势词?

c - 面试题: Longest Prefix That Contains An Equal Number Of Two Integers

java - 用Java递归求和整数

unit-testing - 在 VSCode 中向 F# 项目添加单元测试