Adding stuff to a list in f#
f#
Solution
List in F# are immutable. This means that when you add item to list like this:
let newlist = elem :: tail;;
old list (tail) doesn't changes, instead of that new list created. So, you need to return new list from your `addToList` function and than update mutable variable:
let addToList (listan:List<RectangleZ>) (element:RectangleZ) = element::listan
ShapeList <- addToList ShapeList newElement
In your code `let ShapeList` is local and doesn't affect global ShapeList variable.
Problem
I'm doing a project called "2D Shape editor" in f#. I have done this project in c# before so I've got all the logics for how to connect two shapes. So I know that i will need a list to hold all theese shapes that I will be adding. But I simply can't get my addToList method to work. My ShapeList: ``` let mutable ShapeList:List<RectangleZ> = [RectangleZ(100,100)] ``` My add methods: ``` let addToList (listan:List<RectangleZ>) (element:RectangleZ) = let ShapeList = ShapeList@[element] in ShapeList //Method to add into the ShapeList let addToList (listan:List<RectangleZ>) (element:RectangleZ) = element::ShapeList //Other try on adding into shapeList ``` the button that should be adding rectangles to the ShapeList: ``` btn.Click.Add(fun _ -> new RectangleZ(500, 100) |> addToList ShapeList |>ignore |> saver) //Button click method that should be adding the RectangleZ(500, 100) to my ShapeList ``` And ofcourse my rectangle: ``` type RectangleZ(x:int, y:int)= let mutable thisx = x let mutable thisy = y let mutable thiswidth = 50 let mutable thisheight = 20 let brush = new SolidBrush(Color.Black) member obj.x with get () = thisx and set x = thisx <- x member obj.y with get () = thisy and set y = thisy <- y member obj.width with get () = thiswidth and set width = thiswidth <- width member obj.height with get () = thisheight and set height = thisheight <- height member obj.thisColor = Color.FromArgb(167, 198, 253) member obj.draw(paper:Graphics) = paper.FillRectangle(brush, thisx, thisy, 50, 20) member obj.ShapeType = "Rectangle" ``` The element dosn't get added into the list for some reason in neither of my addToList functions. My Question is why?