Why use references in this scenario, in F# - f#

I found this code online:
let tripleWise (source: seq<_>) =
seq {
use e = source.GetEnumerator()
if e.MoveNext() then
let i = ref e.Current
if e.MoveNext() then
let j = ref e.Current
while e.MoveNext() do
let k = e.Current
yield (!i, !j, k)
i := !j
j := k
}
it's similar to pairwise, but makes triplets.
I am curious as to why the author takes a reference on these lines:
let i = ref e.Current
let j = ref e.Current
instead of copying the value, while he copies the value directly in the loop.

The author used as his starting point the implementation of Seq.pairwise. The current code for pairwise looks like this:
let pairwise (source: seq<'T>) =
checkNonNull "source" source
seq { use ie = source.GetEnumerator()
if ie.MoveNext() then
let mutable iref = ie.Current
while ie.MoveNext() do
let j = ie.Current
yield (iref, j)
iref <- j }
The mutable variable is rather strangely named iref. Sure enough, in an earlier version it was a ref cell. Lots of these were replaced with mutable variables in this commit:
https://github.com/dotnet/fsharp/pull/8063
This was mainly done for readability.
Clearly the author had based his code on the earlier version of Seq.pairwise.

I think the direct answer to your question is that i and j need to be mutable, whereas k does not. (The original code was probably written back when reference cells were the standard way to mutate data in F#, rather than the mutable keyword.) Had the author simply taken a copy, those variables wouldn't be mutable.

Related

How do I make a mutable argument in a function through F#?

Sorry for my question but I did not understand the answers that was related to this question so I hope someone can enlighten me further.
I am a new data science student and we are going to learn how to program in the functional language F#. We are learning about algorithms and I wanted to write the algorithms as F# functions to check if my calculations on paper were correct.
I get the following error saying:
"This value is not mutable. Consider using the mutable keyword let mutable n = expression"
My code looks like this:
let loop5( n ) =
let mutable x = 0
while n > 0 do
x <- x + 1
n <- n + 1
printfn "loop5(): x=%i for n=%i" x n
loop5(4)
I'm trying to write a function looking like this (pseudocode):
loop5(n)
x = 0
while n > 0
x = x + 1
n = n + 1
return x
Hope I made a clear question and someone can help me out here :-) Have a nice weekend
You're trying to mutate the loop's parameter n. The parameter is not mutable, so the compiler doesn't let you. That's exactly what the error tells you.
Now, normally, to make the error go away, you'd make the variable mutable. However, you can't make a function parameter mutable, so that's not an option.
Here you want to think what the meaning of your program should be. Does the loop function need to pass the updated value of n back to its caller, or is the whole mutation its internal business? If it's the former, please see #AnyMoose's answer, but from your example and explanation, I suspect it's the latter. If that is the case, simply make a mutable copy of the parameter and work with it:
let loop n' =
let mutable x = 0
let mutable n = n'
...
Separately, I want to point out that your program, as written, would actually loop indefinitely (or until it wraps around the max int value anyway), because instead of decreasing n at each step you're increasing it. If you want your program to actually finish before the next Ice Age, you need to make n decrease with each iteration:
n <- n - 1
Ref cells
Ref cells get around some of the limitations of mutables. In fact, ref cells are very simple datatypes which wrap up a mutable field in a record type. Ref cells are defined by F# as follows:
type 'a ref = { mutable contents : 'a }
The F# library contains several built-in functions and operators for working with ref cells:
let ref v = { contents = v } (* val ref : 'a -> 'a ref *)
let (!) r = r.contents (* val (!) : 'a ref -> 'a *)
let (:=) r v = r.contents <- v (* val (:=) : 'a ref -> 'a -> unit *)
The ref function is used to create a ref cell, the ! operator is used to read the contents of a ref cell, and the := operator is used to assign a ref cell a new value. Here is a sample in fsi:
let x = ref "hello";;
val x : string ref
x;; (* returns ref instance *)
val it : string ref = {contents = "hello";}
!x;; (* returns x.contents *)
val it : string = "hello"
x := "world";; (* updates x.contents with a new value *)
val it : unit = ()
!x;; (* returns x.contents *)
val it : string = "world"
Since ref cells are allocated on the heap, they can be shared across multiple functions:
open System
let withSideEffects x =
x := "assigned from withSideEffects function"
let refTest() =
let msg = ref "hello"
printfn "%s" !msg
let setMsg() =
msg := "world"
setMsg()
printfn "%s" !msg
withSideEffects msg
printfn "%s" !msg
let main() =
refTest()
Console.ReadKey(true) |> ignore
main()
The withSideEffects function has the type val withSideEffects : string ref -> unit.
This program outputs the following:
hello
world
Assigned from withSideEffects function
The withSideEffects function is named as such because it has a side-effect, meaning it can change the state of a variable in other functions. Ref Cells should be treated like fire. Use it cautiously when it is absolutely necessary but avoid it in general. If you find yourself using Ref Cells while translating code from C/C++, then ignore efficiency for a while and see if you can get away without Ref Cells or at worst using mutable. You would often stumble upon a more elegant and more maintanable algorithm
Aliasing Ref Cells
Note: While imperative programming uses aliasing extensively, this practice has a number of problems. In particular it makes programs hard to follow since the state of any variable can be modified at any point elsewhere in an application. Additionally, multithreaded applications sharing mutable state are difficult to reason about since one thread can potentially change the state of a variable in another thread, which can result in a number of subtle errors related to race conditions and dead locks.
A ref cell is very similar to a C or C++ pointer. Its possible to point to two or more ref cells to the same memory address; changes at that memory address will change the state of all ref cells pointing to it. Conceptually, this process looks like this:
Let's say we have 3 ref cells looking at the same address in memory:
Three references to an integer with value 7
cell1, cell2, and cell3 are all pointing to the same address in memory. The .contents property of each cell is 7. Let's say, at some point in our program, we execute the code cell1 := 10, this changes the value in memory to the following:
Three references to an integer with value 10
By assigning cell1.contents a new value, the variables cell2 and cell3 were changed as well. This can be demonstrated using fsi as follows:
let cell1 = ref 7;;
val cell1 : int ref
let cell2 = cell1;;
val cell2 : int ref
let cell3 = cell2;;
val cell3 : int ref
!cell1;;
val it : int = 7
!cell2;;
val it : int = 7
!cell3;;
val it : int = 7
cell1 := 10;;
val it : unit = ()
!cell1;;
val it : int = 10
!cell2;;
val it : int = 10
!cell3;;
val it : int = 10

F# Mutable Variables inside closures - IDictionary.Item

I am trying to iterate through an IDictionary (reasons explained later...) in F#, and round each value to a specified precision. Essentially this is what I'm trying to do:
List.iter (fun(x) -> a.Item(x) <- Math.Round(a.Item(x), input.precision)) (ICollectionToDoubleList a.Keys)
(where ICollectionToDoubleList takes the ICollection a.Keys and casts it to a double list).
However since you can't alter mutable variables inside closures, this doesn't compile.
My first attempt at a solution was this:
List.iter (fun(x) -> let p = Math.Round(a.Item(x), input.precision)
a.Item(x) := p
) (ICollectionToDoubleList a.Keys)
However I'm getting the error:
This expression was expected to have type
'a ref
but here has type
double
on a.Item(x)
I could convert the IDictionary into two lists (or a list of tuples), perform the rounding, and re-cast into an IDictionary, but this seems a bit messy and convoluted.
Any guidance greatly appreciated.
EDIT:
I forgot to mention a was defined as:
let mutable (a : IDictionary<double,double>) = ...
I think you want
a.Item(x) <- p
In F# you use <- to assign to mutable values, whilst := assign to ref values.
You could even use
a.[x] <- p
for a slightly simpler version.
Explaination of what mutable means (it behaves like the opposite of const in C)
let mutable m = [|1|]
let t = [|1|]
m.[0] <- 0
t.[0] <- 0 //neither of these change m or t - only elements so they are fine
m <- [|1;2;3;|] //fine as m is mutable
t <- [|1;2;3;|] //not allowed as t is not mutable
If you are used to const in C, the above are roughly equivalent to
int* m = {1};
const int* t = {1}
note, neither is equivalent to
const int* q const = {1}
which is I think what you thought not mutable meant.
Ok so I've discovered the answer...
I have defined a as:
let mutable (a : IDictionary<double,double>) = ...
If I change this to
let (a : IDictionary<double,double>) = ...
then this compiles. It seems a little counter-intuative to me that a non-mutable value can be mutated, but a mutatable variable cannot!!

looping through F# record like Javascript object

In javascript, I can access every property of an object with a simple for loop as follows
var myObj = {x:1, y:2};
var i, sum=0;
for(i in myObj) sum = sum + myObj[i];
I am wondering if I can do similar thing with F#.
type MyObj = {x:int; y:int}
let myObj = {x=1; y=2}
let allValues:seq<int> = allPropertyValuesIn myObj //How do I implement allPropertyValuesIn
let sum = allValues |> Seq.fold (+) 0
Thank you for your input
Edit to clarify why I want to do such thing
I am working on an XML file generator. The input is rows read from Database, and the xsd is predefined.
Lets say I have a "Product" Element needs to be generated and depending on the business rule, there could be 200 Children element under product some are required, some are optional. Following the advise from this excellent blog, I have had my first (very rough) design for product record:
1. type Product{ Price:Money; Name:Name; FactoryLocation:Address option ... }
2. let product = {Price = Money(1.5); Name = Name ("Joe Tooth Paste"); ... }
3. let child1 = createEl ("Price", product.Price)
..
203. let allChildren = child1
::child2
::child3
..
::[]
404. let prodctEl = createElWithCildren ("Product", allChildren)
This is very tedious and un-succinct. There HAS to be a better way to do such thing in F#. I am not very kin on the reflection idea either.
Are there any other approaches or I am just doing it wrong?
Try this:
open Microsoft.FSharp.Reflection
type MyObj = {x:int; y:int}
let myObj = {x=1; y=2}
let allValues = FSharpType.GetRecordFields (myObj.GetType())
let sum =
allValues
|> Seq.fold
(fun s t -> s + int(t.GetValue(myObj).ToString()))
0
printfn "%d" sum
However, as John Palmer admonishes, there are not very many good reasons for doing something like this.

two dimensional array - significance of [|[||]|]

Two functions are defined:
let to2DStrArray (inObj : string[][]) =
Array2D.init inObj.Length inObj.[0].Length (fun i j -> inObj.[i].[j])
let toTypedList typeFunc (strArray : string[,]) =
if (Array2D.length1 strArray) = 0 then
[]
else
List.init (Array2D.length1 strArray) typeFunc
trying to call them from fsx as follows fails:
let testData = to2DStrArray [|[||]|]
let failingCall = testData
|> toTypedList (fun row -> (Double.Parse(testData.[row,0]),
Double.Parse(testData.[row,1])))
What is a working/better way to get this code to handle the case of empty 2-dimensional string arrays?
The problem is not in toTypeList function so you don't have to check whether strArray is empty or not. It will give an error if you check inObj.[0].Length in to2DStrArray function when the input array is empty. A safe way to create an Array2D from an array of array is using array2D operator:
let to2DStrArray (inObj : string[][]) =
array2D inObj
Of course, you have to guarantee that all inner arrays have the same length. And the other function is shortened as follows:
let toTypedList typeFunc (strArray : string[,]) =
List.init (Array2D.length1 strArray) typeFunc
Given your use case, note that [|[||]|] is not an empty string[][]; it is an array which consists of only one element which in turn is an empty string array. Therefore, it causes a problem for the anonymous function you passed to toTypedList. Since the two dimensional array has length2 <= 1 and you accesses two first indices, it results in an index of bound exception. The function could be fixed by returning option values, and you can extract values from option values to use later on:
let testData = to2DStrArray [|[||]|]
let failingCall = testData
|> toTypedList (fun row -> if Array2D.length2 testData >= 2 then Some (Double.Parse(testData.[row,0]), Double.Parse(testData.[row,1])) else None)
Realistically you will have another problem as testdata.[0].Length <> testdata.[1].Length - unless you know this from somewhere else. I suspect that the best approach
let ysize = (inobj |> Array.maxBy (fun t -> t.Length)).Length
I quickly tested this and it seems to work - although it may still fail at the point where you access the array

F# mutable function arguments

Is there a way to have mutable function arguments in F#, that would allow something like
let mutable i = 9
let somefun n = n <- 12; ()
somefun i
(* *not* a real-world example *)
I do understand that this can be made to work by wrapping it into a record type
type SomeRec = { mutable i: int }
let ri = { i = 9 }
let someotherfun r = r.i <- 12; ()
and that this can be done in a similar fashion for class members. However, even after browsing through the whole F# Language Specification (yes, I did!), there seems to be no syntax to allow the first case, and the compiler appears to be quite unhappy about my trying this. I was hoping there would be some sort of type annotation, but mutable cannot be used in such.
I also know that I should not be doing this sort of thing in the first place, but the first case (int binding) and the second (record type) are semantically identical, and any such objection would hold for both cases equally.
So I think that I am missing something here.
You can use ref as arguments
let v = ref 0
let mutate r =
r := 100
mutate v
printfn "%d" !v
Or byref keyword
let mutable v = 0
let mutate (r : byref<_>) =
r <- 100
mutate &v
printfn "%d" v
Use byref keyword which is equivalent to C# ref.
See Passing by reference.

Resources