F# - 预计是选项但有类型

时间:2015-07-07 11:29:47

标签: f#

我试图在F#中构建一个二叉树,但是当我尝试测试我的代码时,我遇到了上面的问题。

这是我的代码:

type TreeNode<'a> = { Key: int; Val: 'a }
type Tree<'a> =  { LT: Tree<'a> option; TreeNode: TreeNode<'a>; RT: Tree<'a> option; }

//insert a node according to Binary Tree operation
let rec insert (node: TreeNode<'a>) (tree: Tree<'a> option) =
    match tree with
    | None -> {LT = None; RT = None; TreeNode = node }
    | Some t when node.Key < t.TreeNode.Key -> insert node t.LT
    | Some t when node.Key > t.TreeNode.Key -> insert node t.RT

let t = seq { for i in 1 .. 10 -> { Key = i; Val = i } }|> Seq.fold (fun a i -> insert i a) None

2 个答案:

答案 0 :(得分:1)

您的insert功能需要option<Tree<'T>>,但会返回Tree<'T>。执行fold时,您需要保持相同类型的状态 - 因此,如果要使用None来表示空树,则状态必须是可选类型。

解决此问题的方法是将insert的结果包装在Some中:

let tree = 
  seq { for i in 1 .. 10 -> { Key = i; Val = i } }
  |> Seq.fold (fun a i -> Some(insert i a)) None

答案 1 :(得分:0)

我现在已经解决了......它应该如下所示:

&#xA;&#xA;
 类型TreeNode&lt;'a&gt; = {Key:int; Val:'a}&#xA;输入树&lt;'a&gt; = {TreeNode:TreeNode&lt;'a&gt ;; RT:树&lt;'a&gt;选项; LT:树&lt;'a&gt;选项; }&#xA;&#xA; //根据二叉树操作插入节点&#xA;让rec插入(节点:TreeNode&lt;'a&gt;)(树:树&lt;'&gt;选项)=&#xA;匹配树&#xA; |无 - &gt; {LT =无; RT =无; TreeNode = node}&#xA; |当node.Key&lt; t.TreeNode.Key  - &gt; {TreeNode = t.TreeNode; LT =一些(插入节点t.LT); RT = t.RT}&#xA; |当node.Key&gt;时有些t.TreeNode.Key  - &gt; {TreeNode = t.TreeNode; RT = Some(插入节点t.RT); LT = t.LT}&#xA;&#xA;令t = seq {for i in 1 ... 10-&gt; {Key = i; Val = i}} |&gt; Seq.fold(有趣的i  - &gt; Some(插入i))无&#xA;  
&#xA;