F# Change element in list and return full new list

大憨熊 提交于 2019-12-05 12:45:13

Lists are immutable, so if you want to "change one element" you are really creating a new list with one element transformed. The easiest way to do a transformation like this is to use List.map function. I would write something like:

let updateElement key f st = 
  st |> List.map (fun (k, v) -> if k = key then k, f v else k, v)

updateElement is a helper that takes a key, update function and an input. It returns list where the element with the given key has been transformed using the given function. For example, to increment the first number associated with a2, you can write:

let st = [("a1",(100,10)); ("a2",(50,20)); ("a3",(25,40))]

st |> updateElement "a2" (fun (a, b) -> a + 10, b)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!