gpt4 book ai didi

f# - 在f#中向列表添加内容

转载 作者:行者123 更新时间:2023-12-03 23:22:04 24 4
gpt4 key购买 nike

我正在f#中执行一个名为“ 2D Shape editor”的项目。之前我已经在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函数都没有将该元素添加到列表中。我的问题是为什么?

最佳答案

F#中的列表是不可变的。这意味着当您将项目添加到列表中时,如下所示:

let newlist = elem :: tail;;


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

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


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

关于f# - 在f#中向列表添加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13839336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com