Does the following code simulate the difference between protected variables and public variables in F#? Or am I missing something?
let (=?) (d:Dictionary<'a,'b>) (x:'a) = d.TryGetValue(x)
let psi (f:'a -> 'b) (d:Dictionary<'a,'b>) = // public dictionary
let lambda (x:'a) =
match (d =? x) with
| true, i -> i
| false, _ -> d.Add(x,f x)
f x
lambda
let mem (f:'a -> 'b) = // protected dictionary
let d = new Dictionary<'a,'b>()
let orize (input:'a) =
match (d =? input) with
| true, i -> i
| false, _ -> d.Add(input,f input)
f input
orize
Clarification would be excellent.
No, what you actually demonstrate is scope of values in F#.
In the first approach, the dictionary is declared at the module level; therefore, any function in the module can access/modify it. The point is more clear if you drop that second argument in the
psifunction. After each timepsiinvoked, the dictionary is still available andpsiis a true memoize combinator.The second approach has dictionary declaration inside a function, and the scope of this dictionary is the function only. Each time you call
mem, it creates a fresh dictionary so you don’t really memorize anything.In terms of access modifier, your example is closer to
public/privatevalues. These keywords are available in F#. Theprotectedmodifier is related to inheritance which you will encounter much less often in F#. And it’s another story to tell.