0
let source =  [|(CocaCola, bigBottle); (CocaCola, smallCup); (Tuborg, smallCup)|]


//the method can't store the updated array. 
let  mkOrder (dr:liquid ,cont:Containment) = Array.append source [|(dr, cont)|]

Hello I have a method here to append a new item to the source array. However, the method doesn't store the updated array and thus, only works once I've tried multiple different but none of them has worked.

2 Answers 2

2

The F# arrays are

fixed-size, zero-based, mutable collections of consecutive data elements that are all of the same type

So this means that while you can change the value of the element at position n you can't extend the array to have more elements. So what your mkOrder function is doing is taking your array source and creating a new array by appending the new element to it, unless you capture this new array that is returned by mkOrder it will be lost. If you open up an interactive window and try the following:

> let array1 = [| 1; 2; 3 |];;
val array1 : int [] = [|1; 2; 3|]

> let array2 = Array.append array1 [|4|];;
val array2 : int [] = [|1; 2; 3; 4|]

> array1;;
val it : int [] = [|1; 2; 3|]

> array2;;
val it : int [] = [|1; 2; 3; 4|]

The append creates a new array - it doesn't update the existing array.

The MS documentation for F# arrays is here

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to implement the code in a way that when i call it multiple times, it would add all those values to the base array and can give me a new array with all the items added?
Why do you need an array? Use C# List, aka ResizeArray, it has an Add method.
0

Obviously not very idiomatic F# but feel free to clarify on what kind of data structure you need and how you want to use it:

open System.Collections.Generic
let source =  ResizeArray<string * string >( [("CocaCola", "bigBottle"); ("CocaCola", "smallCup"); ("Tuborg", "smallCup")])
source.Add("Beer", "XL")
source

val it : ResizeArray = seq [("CocaCola", "bigBottle"); ("CocaCola", "smallCup"); ("Tuborg", "smallCup"); ("Beer", "XL")]

ResizeArray is an alias for C#'s List which is a mutable and resizable array. You can add, remove and do most of the stuff need to with an IEnumerable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.