Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
F# 使用列表中的参数由函数多次更新记录_F# - Fatal编程技术网

F# 使用列表中的参数由函数多次更新记录

F# 使用列表中的参数由函数多次更新记录,f#,F#,我所拥有的: type Item = { Name : string } type Model = { Items : Item list } let init = { Items = [] } type Msg = |AddItem |DoNothing let update msg model = //Msg -> Model -> Model match msg with |AddItem -> {m

我所拥有的:

type Item = 
  {
    Name : string
  }

type Model = 
  { 
    Items : Item list
  }

let init = {
  Items = []
  }

type Msg =
  |AddItem
  |DoNothing

let update msg model =  //Msg -> Model -> Model
  match msg with
  |AddItem -> {model with Items = List.append [{Name = "NewItem"}] model.Items}
  |DoNothing -> model

let rec apply f model list = //(a' -> 'b -> 'b) -> 'b -> 'a list -> 'b
        match list with
        |[] -> model
        |head::tail -> let model' = f head model
                       apply f model' tail

let msgs = [AddItem; DoNothing; AddItem]

let model' = apply update init msgs
给出了结果:

val model' : Model = { Items = [{ Name = "NewItem" }; { Name = "NewItem" }] }
我已经检查了fold、map和其他一些函数,但是看起来这些函数中没有一个与我的apply做的相同


在列表或其他地方是否有与我的apply相同的内置函数?因为如果有,我更愿意使用它。

您的
apply
函数与
List相同。按不同的顺序折叠带参数的累加器函数。
apply
的类型为:

(a' -> 'b -> 'b) -> 'b -> 'a list -> 'b
(b' -> 'a -> 'b) -> 'b -> 'a list -> 'b
List.fold的类型为:

(a' -> 'b -> 'b) -> 'b -> 'a list -> 'b
(b' -> 'a -> 'b) -> 'b -> 'a list -> 'b
因此,您可以将对
apply
的调用替换为:

List.fold (fun model msg -> update msg model) init msgs

这看起来与
List.fold
相同,参数以另一种顺序指向
f
,即
List.fold(fun model msg->update msg model)init msgs
@Lee Perfect!回答这个问题,我会接受的。伙计,真的很难理解,对于我这样的noob来说,如何使用标准函数。