递归F#中的不变性 [英] Recursion & Immutability in F#

查看:77
本文介绍了递归F#中的不变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简单示例:

type Parent = { Children : Child list }
and Child = { Value : int ; Parent : Parent }

let rec children = [ { Value = 0 ; Parent = parent } ]
and parent = { Children = children }

F#编译器足够聪明,可以正确地初始化这些递归对象,可以通过运行来验证

The F# compiler is smart enough to correctly initialize these recursive objects, as can be verified by running

obj.ReferenceEquals(parent, parent.Children.Head.Parent)

现在,考虑以下概括:

let length = 100 // assume arbitrary

let rec children = List.init length (fun i -> { Value = i ; Parent = parent })
and parent = { Children = children }

此定义将导致编译器错误.我的问题如下:有什么办法可以使上述绑定没有依靠反射或可变字段?

This definition will result in a compiler error. My question is the following: is there any way I could make the above binding without resorting to reflection or mutable fields?

推荐答案

let rec mkChild i = {Value = i; Parent = parent}
and parent = { Children = children }
and children = List.init length mkChild

这篇关于递归F#中的不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆