我在f#中正在做一个名为“2D形状编辑器”的项目。我之前在c#中完成了这个项目,所以我已经掌握了如何连接两个形状的所有逻辑。所以我知道我需要一个列表来保存我将要添加的所有形状。但我根本无法让我的addToList方法起作用。
我的ShapeList:
let mutable ShapeList:List<RectangleZ> = [RectangleZ(100,100)]
我的添加方法:
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
应该将矩形添加到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
当然是我的矩形:
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"
由于某些原因,我的addToList函数都没有将元素添加到列表中。我的问题是为什么?
答案 0 :(得分:15)
F#中的列表是不可变的。这意味着当您将项目添加到列表中时:
let newlist = elem :: tail;;
旧列表(尾部)不会更改,而是创建新列表。因此,您需要从addToList
函数返回新列表,然后更新可变变量:
let addToList (listan:List<RectangleZ>) (element:RectangleZ) = element::listan
ShapeList <- addToList ShapeList newElement
在您的代码中let ShapeList
是本地的,不会影响全局ShapeList变量。
答案 1 :(得分:2)
let newList = oldList @ [newElement]
答案 2 :(得分:1)
您可以将List.append
与mutable
列表一起使用,下面的示例与我合作正常:
let mutable season_averages = []
for i in 0 .. n_seasons do
season_averages <- [i] |> List.append season_averages
printfn "Seasons Average: %A" season_averages