How to edit an Item in a mutable list in f# and allow the other items in the list retain their values?

Cha*_*uuu 4 f# list mutable

I created a list in f# named tickets that contains 10 records called Ticket.The records are all initialized with their specific seat number and empty customer name.

type Ticket = {seat:int; customer:string}  
let mutable tickets = [for n in 1..10 -> {Ticket.seat = n; Ticket.customer = ""}]
Run Code Online (Sandbox Code Playgroud)

I want to write a function to book a specific seat in the list(add a customer name to the seat). How can i edit an item in the list and have other items still retain their value

Tom*_*cek 5

函数式 F# 列表类型是不可变的,这意味着您无法更改它。使用它的典型方法是返回一个新的、修改过的副本。

要做到这一点,您可以编写一个函数bookSeat,将list<Ticket>数字和新名称结合在一起,并生成一个更新list<Ticket>了该字段的新函数:

let bookSeat seatNo name tickets = 
  tickets |> List.map (fun ticket ->
    if ticket.seat = seatNo then { ticket with customer = name }
    else ticket )

bookSeat 3 "Tomas" tickets
Run Code Online (Sandbox Code Playgroud)