20

我正在 f# 中做一个名为“2D 形状编辑器”的项目。我之前在 c# 中做过这个项目,所以我已经掌握了如何连接两个形状的所有逻辑。所以我知道我需要一个列表来保存我将添加的所有这些形状。但我根本无法让我的 addToList 方法工作。

我的形状列表:

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 函数中,该元素都没有被添加到列表中。我的问题是为什么?

4

3 回答 3

27

F# 中的列表是不可变的。这意味着当您像这样将项目添加到列表时:

let newlist = elem :: tail;;

旧列表(尾部)不会更改,而不是创建的新列表。因此,您需要从addToList函数中返回新列表,而不是更新可变变量:

let addToList (listan:List<RectangleZ>) (element:RectangleZ) = element::listan
ShapeList <- addToList ShapeList newElement

在您的代码let ShapeList中是本地的,不会影响全局 ShapeList 变量。

于 2012-12-12T12:19:11.693 回答
19
let newList = oldList @ [newElement]
于 2018-08-03T04:50:27.763 回答
3

您可以List.appendmutable列表一起使用,下面的示例对我来说效果很好:

let mutable season_averages = []
for i in 0 .. n_seasons do
     season_averages  <- [i] |> List.append season_averages
printfn "Seasons Average: %A" season_averages
于 2018-01-12T18:28:00.400 回答