简体   繁体   English

Haskell:通过计算列表的每个值来更新状态的函数

[英]Haskell : A function that updates a state by calculating with each value of a list

I need a function that updates a state multiple times depending on a list of values: for each value of the list it may possibly update the state or leave it unchanged. 我需要一个根据值列表多次更新状态的函数:对于列表的每个值,它可能会更新状态或保持不变。 So I figured I'd need a function of a type like: 所以我想我需要一个像这样的函数:

[a] -> b -> (a->b->b) -> b

Where [a] is a list of values for which goes that for each of them the state b may be updated (depending of the value of a). 其中[a]是值列表,对于每个值,状态b均可更新(取决于a的值)。 Then the resulting b is a new state that has all necessary updates applied. 然后,生成的b是已应用所有必要更新的新状态。

However I could not find any function that on Hoogle that does this, so I figure I'd have to make one myself however I have no idea how I could do this. 但是,我找不到在Hoogle上执行此操作的任何函数,因此我认为自己必须自己做一个,但是我不知道该怎么做。 Are there any functions existing that I can use to accomplish such function? 我可以使用任何功能来完成此功能吗?

If anyone could help me out on this it'd be much appreciated! 如果有人可以帮助我,将不胜感激!

Best regards, Skyfe. 最好的问候,Skyfe。

EDIT: A (simplified) example of what I could have & need: 编辑:我可以拥有并需要的(简化)示例:

[a] = [1, 5, 3, 6]
b   = State{x, y, z}
f :: (a->b->b)
f a b = if someAlgorithm a then b{x=someFunc x, y=y+1} else b

=> Then the function I need should execute f on all a's and for each time it does so, it should return the new (updated or unchanged) b as argument for the new call to f along with the next element from the list [a], and so on untill it has done this for all elements and results into a final b with all updates applied. =>然后,我需要的函数应在所有a上执行f,并且每次执行f时,都应返回新的(更新或未更改的)b作为对f的新调用的参数以及列表中的下一个元素[a ],以此类推,直到对所有元素执行此操作,并在应用所有更新的情况下生成最终的b。

What you want is foldr fba after applying filter someAlgorithm on your list. 在列表中应用filter someAlgorithm后,您需要的是foldr fba If you don't know these functions, look them up on hoogle. 如果您不了解这些功能,请大声疾呼。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM