0

How to de/reference the 3 array variables in this code instead of using mutable values?

The code below computes the Longest common subsequence (LCS) by diagonal traversing the m*n array.

The arguments are 2 char arrays like so:

So LCS method should result to length 4 as the longest common sub-sequence chars are "acbb" & "bcbb".

let private s1 = "ABCDBB".ToCharArray()    
let private s2 = "CBACBAABA".ToCharArray()
    let public lcs_seq_1d_diags (x:char[]) (y:char[]) = 
        let m = x.Length
        let n = y.Length

        let mutable dk2 = Array.create (1+m) 0
        //printfn "\r\n0: %A" dk2
        let mutable dk1 = Array.create (1+m) 0
        //printfn "1: %A" dk1
        let mutable dk = Array.create (1+m) 0

        for k = 2 to m+n do
            let low = max 1 (k-m)
            let high = min (k-1) n

            for j = low to high do
                let i = k - j
                if x.[i-1] = y.[j-1] then
                    dk.[i] <- dk2.[i-1] + 1
                else 
                    dk.[i] <- max dk1.[i] dk1.[i-1]

            let mutable temp = dk2
            dk2 <- dk1
            dk1 <- dk
            dk <- temp

        dk1.[m]

let private res_seq_1d_rows = duration (fun () -> lcs_seq_1d_rows s1 s2)
//res_seq_1d_rows = 4
  • Mutability is determined by the data type -- if you want to use System.Array then you need to expect/deal with mutability. – ildjarn Apr 15 '13 at 03:58

2 Answers2

0

Take a look at the reference cells http://msdn.microsoft.com/en-us/library/dd233186.aspx

The syntax looks like this:

let a = ref 1 // declaring a reference
a := 2 // changing the reference value
printfn "%i" !a // dereferencing

This might also be interesting: F#: let mutable vs. ref

Community
  • 1
  • 1
MisterMetaphor
  • 5,900
  • 3
  • 24
  • 31
0

Arrays are mutable by default. Try using a list instead if you want immutability.

Try starting with this instead:

let s1 = List.ofSeq "ABCDBB"
let s2 = List.ofSeq "CBACBAABA"

The rest I leave as an exercise for the reader :-)

Onorio Catenacci
  • 14,928
  • 14
  • 81
  • 132