繁体   English   中英

在clojure中,您可以将函数应用于集合中的所有元素,并让返回值作为下一个的输入吗?

[英]In clojure can you apply a function to all elements in a collection and have the return value be the input for the next?

假设您有一个这样的集合({A: 1 B: 2} {A: 2 B: 5} {A: 4 B: 7})其中包含未指定数量的{A:B:}部分和一个函数(func arg1 arg2)

如果我们假定有一些初始状态state ,并且每一个呼叫func生成一个new-state 是否可以构造类似这样的行为?

(->(func state {A: 1 B: 2})
(func {A: 2 B: 5}) 
(func {A: 4 B: 7}))

基本上,第一个参数是新状态,第二个参数是集合中的下一个{A: B:}

任何帮助,将不胜感激!

是的,此函数称为reduce

(reduce
  func
  initial-state
  input-sequence)

或使用输入序列的第一个元素作为初始状态的版本(请查看函数doc以查看其行为的详细信息):

(reduce 
  func
  input-sequence)

例如:

(reduce
  +
  100
  [1 2 3 4 5])
;; => 115

(reduce
  +
  [1 2 3 4 5])
;; => 15

暂无
暂无

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

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