簡體   English   中英

Wolfram語言在ClojureScript中的折疊相當於什么?

[英]What is the equivalent of Wolfram Language's Fold in ClojureScript?

在Wolfram語言中,又名Mathematica(Lisp)

Fold[g, 0, {a,b,c}]

評估為

g[g[g[0,a],b],c]

所以什么時候

f[x_,y_]:=10 x + y

然后

Fold[f, 0, {1,2,3,4}]

評估為(根據數字創建一個數字)

1234

在ClojureScript中,Wolfram語言的Fold等效於什么?

干得好:

(reduce 
  (fn [r x] (+ (* r 10) x)) 
  0 [1 2 3 4])

數學函數對折有幾種折法,左折和右折在功能應用的方向上有所不同。 Clojure的減少量左折

同樣在clojure中,與其他具有fold的語言相比,reduce函數將使用幾個不同數量的參數來調用。

首先讓我們定義一個告訴我們參數的函數

user> (defn ++ [& args]
        (println "++ called with" args)
        (apply + args))
#'user/++

如果列表為空,則不帶任何參數調用reduce函數以產生“ identity”值。 對於附加身份為零,對於/為1,依此類推。

user> (reduce ++ [])
++ called with nil
0

對於單個項目列表,根本不會調用

user> (reduce ++ [1])
1

在其余情況下,將使用兩個參數調用該函數,並像在左邊關聯的運算符(使用inflix語言)中一樣使用該函數,或者僅在lisp中調用一個普通的舊函數。

user> (reduce ++ [1 2])
++ called with (1 2)
3
user> (reduce ++ [1 2 3])
++ called with (1 2)
++ called with (3 3)
6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM