[Question]
  [
[Inspiration.](https://chat.stackexchange.com/transcript/message/42442315#42442315)
Given (by any means):
* A two-argument (or single argument consisting of a two-element list) [black box function](https://codegolf.meta.stackexchange.com/a/13706/24877), `f: ℤ+ × ℤ+ → ℤ+` (input and output are 1, 2, 3,…)
* A strictly positive integer matrix with at least two rows and two columns
return the matrix's *function trace*.
What is a *function trace*?
A normal matrix trace is the sum of the major diagonal (top-left to bottom-right) of a matrix:
`[[1,2,3],[4,5,6],[7,8,9]]` → `[1,5,9]` → `1+5+9` → `15`
But instead of summing, we want to apply `f` along the diagonal:
`[[1,2,3],[4,5,6],[7,8,9]]` → `[1,5,9]` → `f(f(1,5),9)` or `f(1,f(5,9))`
Please state whether you use left-to-right or right-to-left.
The given matrix and all intermediate values will be strictly positive integers within your language's integer domain. The matrix may be non-square.
### Examples
`f(x,y) = xy`, `[[1,2,3],[4,5,6],[7,8,9]]` → `1×5×9` → `45`
`f(x,y) = xy`, `[[1,2,3],[4,5,6],[7,8,9]]` → `159` → `1`
`f(x,y) = x-y`, `[[4,5,6],[1,2,3]]` → `4-2` → `2`
`f(x,y) = (x+y)⁄2`, `[[2,3,4],[5,6,7],[8,9,10]]` → `5` or `7`
`f(x,y) = x+2y`, `[[1,2,3],[4,5,6],[7,8,9]]` → `47` or `29`
`f(x,y) = max(x,y)`, `[[1,2,3],[4,5,6],[7,8,9]]` → `max(1,5,9)` → `9`
`f(x,y) = 2x`, `[[1,2,3],[4,5,6],[7,8,9]]` → `2` or `4`
`f(x,y) = lcm(x,y)`, `[[2,2,2],[2,2,3],[2,3,3],[4,4,4]]` → `lcm(2,2,3)` → `6`
[Reference implementation.](https://tio.run/##nZJBa9swFMfv@hTvlq1RYFbtZqnPG3SM7tDSS/BBOLYrcORiu1tD2WWDNg11KYOS0y677AOUMug130RfJHuS7MQb6SU2QQ@////3/lLEz9LeaMLTLFku1fT6M0/PI3V1H0s4znkYwZiXubjw8@xL4YdZWvgjwZOPkUzKU1/IUeELP43i8kCXujjhqVmP0CYTPxfJqW2aSndNUbeji7OcgIbjTHXzy06D5lHVTyh5mk4I6NlWo2bf/5WtVBCLvCgJrCOiw8BvZ9pvlGMhxfh8TECn18Tqca3vOTUPmyKMCkJg/32Wg4D9A2kcxIxstox@AWL9DfeHn2y8oZp9a3TBWmJ3bgY/1JbWPgrTFfGEWMfq/NDQwLpOq/f/xJUhaInaMxtXPUD/AzXbqmgsactkUoWZDHkZSfxZV3NNVHWnAbDh0b5I61amTSGRYVh4zu/kCI@a4CVcLjuXqnpezFX19LVTX0R19/Dh6NMhdIZDhzK6G9ChSz26h2ufvqWDIOiYmerqBziLubeYD0ztesTQdraGeRbkWE7vBU7jt7yW3@0xszL0v0JAFwGvF3/YJghaqYsQRNE@rhiFOm/aNA/wOvZtlC7b/ojcvgaxgSWp2@m2IE0wOZ63sjMdw61TTH@/kIIhhqGd1Th9ThaLbxu39xc "APL (Dyalog Unicode) – Try It Online")
  
[Answer]
# [R](https://www.r-project.org/), ~~40~~ 30 bytes
```
function(m,F)Reduce(F,diag(m))
```
[Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP08jV8dNMyg1pTQ5VcNNJyUzMV0jV1Pzf5pGbmJJUWaFhpGVoYGOMRAmVRbll9uGaOrAdVboVGpqVGhXauobaXLBNSRrmFiZ6RhaGWvq5IF0GCF0JugmaP4HAA "R – Try It Online")
[Verify the test cases.](https://tio.run/##jY9BC4JAFITv/grxtE@flLsStOQp8FSX6BzoqiG0K2xKu79@06DQi8Qwp/mY90a7xj/EvmsGJfq2U0RiDpe6GkRNcqza4k4kgGuILHrdGpLwPbJRpdXdK7sCBmEA3kp8m8eCpHyHCWeAagLoDIznIOXJdln0e9CgBWIiCxu6dnjBm4iGdo2Whfm7jIZmMYniV@xjhumkcaLoHtmsRQ2yrPWT89PxDJ57Aw "R – Try It Online")
Traverses down the diagonal, so left-to-right in this case. For arithmetic operators, you can use `"+"` or backticks around the operators (`+,*,-,%/%,^,%%`)
Pretty straightforward: `Reduce` is R's equivalent to a `fold`, and ~~the diagonal of a matrix is those elements `a_ij` where `i==j`, i.e., where the `row` and `col`umn indices are the same.~~ `diag` has the appropriate behavior for non-square matrices.
[Answer]
# [Haskell](https://www.haskell.org/), 39 bytes
Thanks @Laikoni for helping me fix the previously invalid solution!
```
f!m=foldl1 f[h|h:_<-zipWith drop[0..]m]
```
Associates to the left, [try it online!](https://tio.run/##Rc69TsMwFAXgPU9xanWwiVPRQvmpki6sMDEwuBZ16phYJHaUOCAh3j04DO10rr57dXRrNXxWTTNNZtEWxje6WcOI@rfevefZj@3ebKihe9@J69VKtnJqlXUooH0CWNeNAXmGvlIa@XKPjyo8eRcqF4a4b1X3AnqgxnHDsj3i9Wvonx2WMA5pCrIDmXOo/TeoWfwXMgYzulOw3g1Jch5RxEYBSpTWhIOmDCxKnMgwlrNkF2nHZpari2j7FeWgUCJ@QhVSlAzHyEds5iM5CbHmG34jubjlW34X854/8Ecp/wA "Haskell – Try It Online") (replace `foldl1` by `foldr1` for right-associative)
[Answer]
# [Mathematica](https://www.wolfram.com/mathematica/), 16 bytes
*-1 byte thanks to Martin Ender.*
```
#~Tr~Fold[g]@*0&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7kupKjOLT8nJTo91kHLQO1/uoKtgrKCloKykYIaF1dAUWZeSXSagoNCdbWhjoKRjoJxrY5CtYmOgqmOghmIaa6jYKGjYFlbG/sfAA "Wolfram Language (Mathematica) – Try It Online")
## Alternate solution, 17 bytes
```
Fold[g]@*Diagonal
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0/JyU6PdZByyUzMT0/LzHnf7qCrYKygpaCspGCGhdXQFFmXkl0WnR1taGOgpGOgnGtjkK1iY6CqY6CGYhprqNgoaNgWVsbG/sfAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~61~~ ~~57~~ 53 bytes
```
function m=g(f,m)for i=diag(m)'(2:end)m=f(m(1),i);end
```
[Try it online!](https://tio.run/##jZDRTsMgFIav16c4N4uwnalgu9otTXwCr7xbZkI6mCSDxrXT7gV8AG/2QHsTX6RCqxPvGkIOBL6Pn1MWtXiTbasOtqh1acHkW6LQUFXuQecbLbbE0CvCF9JuqMkVMYRR1HTp9q2bMIbHsoa9fD3ovdyAVlC/SLj43kUFRWlroa0/tSAsXBtQeiejaPwkq7oQlawWUaTyB9LgkUIzOeJo5GPAasWQ4916uYoxwbmrKd5jtl7TMXx9fAI7n5LzKevWcRI6ngc4oJcAS3oDCwWzQPAL9qILGM94V3nAkWZ6pDccf1EHYOxQJ8DUVfcystvuAx2bgGt0Gj485cP@30dIPc@zQGBE0y1woMLfZ@4oo902VPFJMzgJ90HiAN4V5n8O7gTcgfxH5FvTC93466rnuit9nnnUfgM "Octave – Try It Online")
Defines a function `g` which takes a function handle `f` and matrix `m`.
On the first iteration, `m(1)` returns the top-left matrix element; after that, it just returns `m`. 
[Answer]
# [Clean](https://clean.cs.ru.nl), 56 bytes
```
t[[h:_]]f=h
t[[h]:_]f=h
t[[h:_]:r]f=f h(t[t\\[_:t]<-r]f)
```
[Try it online!](https://tio.run/##NYw7D4IwFIV3fkXHVi@JxTeRTQcTN8ZSTcNDmtBC4Gr0z1uvg8PJ@b4znLKrjQ@urx5dzZyxPqBSbXrTusna6Mea5M@E6UjWsJajwqJQtxT1IaZNBOuGfkSWY3XyzyhHQ5LR58A4MqUkJLDUoFawhg31Fnawp5YLkBJkorVgis8F8Jgyo1wFOOvBmZcOn7LpzH0K8fkSjm9vnC2nLw "Clean – Try It Online") Folds from right-to-left.
`[t\\[_:t]<-r]` is the same as `map tl r`, but does not need `import StdEnv`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~47~~ ~~45~~ 42 bytes
```
f%((h:t):r)|[]<-t*>r=h|x<-tail<$>r=f h$f%x
```
[Try it online!](https://tio.run/##FcpNDsIgEEDhvaeYhU1mdGqk/jfFG3gCggkLCcTSNMiiC@6OdPHybZ4zv@9nHEuxDaLrE/WRcpJS6ZzjinR5Gdpk/Dhsn1FacGibhUoACUoJ7vikWZ35wtfqje/8qIojC8Gi03pj1xH3xLirtbU3cfATB7PoTTB@qkMw8wtwjn5KcABsAhHY8gc "Haskell – Try It Online") Defines a function `(%)` which takes a function and a matrix as a list of lists as input. 
The function is folds from right-to-left:
```
f % [[1,2,3], -> f 1 ( f % [[5,6],   -> f 1 ( f 5 ( f % [[9]] ) ) -> f 1 ( f 5 ( f 9 ) ) )
     [4,5,6],               [8,9]] )
     [7,8,9]]
f % ((h:t):r)              -- (h:t) is the first row and r the remaining rows
 | [] <- t *> r = h         -- a shorter way of checking wether t==[] or r==[]
 | x<-tail<$>r = f h $ f%x -- apply f to h and the result of recursively calling (%) on
                           -- the remaining matrix with the first column removed
```
*Edit: -2 bytes thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo) and -3 bytes thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb)!*
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes ([Adám's SBCS](https://github.com/abrudz/SBCS))
```
⎕/1 1⍉⎕
```
[Try it online!](https://tio.run/##hZAxTsMwFIb3nOLfSElLlaYgMSIqJCQGBi7gOqa15NghdhDcoFSEDZhY6EB3kDhAb@KLlNdElaCiMDw9y@/7//fbLFed9JYpM1ouffWCY5MKcKZ3HIYCuWJcpBiLQiAtBZyBE3ysJWcKhbCukNxJo@1eo17VSakU8sKMCpYhtOUwk9YS025smIXUThSMhNe0ymQZ06ltBbX@4bEbI/bVHZ2CteOpzkuHGGHGaOFNgyZIfPXhq/fDDa6HcFA/CEfnZ7gsdZ2wDSEdBYBjXDqYAoPOetYYRkHdLuhV9AFWWIRSgzSwLBOkSElN6Vc3VyVRtWsCJTWxgvEx@fzI/y3i4nn7bHdj5KdPvfX0IOj8KoyjWtpbfPpqHm339tNZ5Kevq/oDup/85zDbAPo1EO4jbhOVtLp96vM@3VH0wE/evgA "APL (Dyalog Unicode) – Try It Online")
-3 thanks to a suggestion to convert this to a full program by [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m).
Right-to-left.
[Answer]
# [Haskell](https://www.haskell.org/), 44 bytes
```
f#m=foldl1 f$zipWith(!!)m[0..length(m!!0)-1]
```
[Try it online!](https://tio.run/##Fcq9DoMgGIXh3as4RAdpvho@@z94HR0Ig0mlEoGa1i69eQrb8@acefwsk/cp2ToM9uUfnmGbn1vvbptbIWTQquv8FJ85gxBK7tmk8PUY0O5kVYXRxez17eKGBmWpoTUTesLBEPSRcCKcCy@EK@FWyIrA@cW9MekP "Haskell – Try It Online")
[Answer]
# [Standard ML (MLton)](http://www.mlton.org/), 59 bytes
```
fun t[h::_]f=h|t([h]::_)f=h|t((h::_)::r)f=f(h,t(map tl r)f)
```
[Try it online!](https://tio.run/##LY07D8IwDIR3foXVKQEXkfKOVHZmxhCqLqWVmodagzrw34sjGKzTdz6fR9fnrqfg57l5eSDTal3Zpmw/JExrGeQPRFpIrQfmRrRIwtURqAc25Pyue3A1Dd0EJRijsMCtRbPDPR5Yj3jCM6vaoFKoCmsX6aLicGoRceg8QQDReBjLy/jI7j6TbFw9rSncuNg/Gen/RIIJcYUh5jxLTCnX@Z/Wk52/ "Standard ML (MLton) – Try It Online") Folds from right-to-left.
### Ungolfed:
```
fun trace [h::_]      f = h
  | trace ([h]::_)    f = h
  | trace ((h::_)::r) f = f (h, trace (map tl r) f)
```
[Try it online!](https://tio.run/##bY1PC8IwDMXvforgqdVMrP8dzLtnj7VKEesGazu2Kjv43We66c1AeCS/95LGloktg3ddZ54OQq1vd5B5ml4V9GUgg3wE8P4yJnNFlP9lLAZ5mta8ZwZYjj9mdQWhhIh499IlWB3qoiWblAIXuFQoV7jGDekWd7gnFXMUAsVCqVFMXMkcz7CqLlwAD8w4aLJDcxmf3ZjT4ujCLPgTHXYPGofXwyMO0ldT9FVCPcHotIUbVLeq@wA "Standard ML (MLton) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
Thanks @Zgarb for fixing my submission!
```
Ḟ₁§z!Tŀ
```
Associates to the left, [Try it online!](https://tio.run/##yygtzv7//@GOeY@aGg8tr1IMOdrwP0H3///oaEMdIx3jWJ1oEx1THTMgba5joWMZGwsA "Husk – Try It Online") (for a right-associative version simply replace `Ḟ` by `F`)
### Explanation
Unfortunately there's no easy way to get the diagonal of a matrix, so most the bytes are for that:
```
Ḟ₁§z!Tŀ  -- function ₁ is the function and matrix A implicit, example: 
  §      -- fork A
     T   -- | transpose A: [[1,4,7],[2,5,8],[3,6,9]]
      ŀ  -- | enumerate A: [1,2,3]
   z!    -- and zipWith index: [1,5,9]
Ḟ₁       -- right fold function
```
[Answer]
# [Python 2](https://docs.python.org/2/), 61 bytes
```
lambda f,m:reduce(f,[l[i]for i,l in enumerate(m)if len(l)>i])
```
[Try it online!](https://tio.run/##bcxNDsIgGIThvadgCWZMav1vohdBFmg/KgnQhtCknB5tbFy5mN3zzpDTqw916a734rR/tJoZ@CZSOz6JG0gnrTJ9ZBaO2cAojJ6iTsS9sIY5CtyJm1WiDNGGxDq@vEzIzbTJkHKPA44KcosaO6XE6p9cz/Ir8CtOOOMyl1WFZZ@@vAE "Python 2 – Try It Online")
This works left-to-right.
[Answer]
## JavaScript (ES6), ~~58~~ 56 bytes
```
g=(f,a,r=a[i=0][0],e=a[++i]&&a[i][i])=>e?g(f,a,f(r,e)):r
```
Folds left-to-right. Edit: Saved 2 bytes by using the fact that the array is strictly positive. Alternate solution, also 56 bytes:
```
(f,a,g=r=>(e=a[++i]&&a[i][i])?g(f(r,e)):r)=>g(a[i=0][0])
```
[Answer]
# JavaScript, 46 bytes
```
f=>a=>a.reduce((p,l,i)=>l[i]?f(p[0]|p,l[i]):p)
```
Thanks to @Shaggy, use bitwise or save one byte. That's magic.
```
g = f=>a=>a.reduce((p,l,i)=>l[i]?f(p[0]|p,l[i]):p)
c=()=>o.value=g(eval(`(x,y)=>${f.value}`))(m.value.split(/\n/g).map(x=>x.trim().split(/\s+/).filter(v=>v.length).map(v=>+v)).filter(x=>x.length))
```
```
<p>a = <textarea id=m>1 2 3
4 5 6
7 8 9</textarea></p>
<p>f = (x, y) => <input id=f type=text value="x + y" /></p>
<p><button onclick=c()>Calc</button></p>
<p>Result = <output id=o></output></p>
```
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), 14 bytes
```
Fold#/Diagonal
```
[Try it online!](https://tio.run/##pZDNCsIwEITvfYqAnnREG/8PSkURBAVPXkLU2KZaKC2UKIL47HVrLUjBS51AdmHzzWZXGaPci04X2g8iLeo@0mUcerX2IlDnOFJhKq2iZlwwYTFSfmc6NsG@JYQNjq6E6KGPAcUhRhhL@SYkyvj@P7xVxgsst/mBzW46UWft7FBg9Bg9wgjGkCL1hN35yXvZguLrKdSo8OuNuuOPoR@8cXiiMr6eb0rdOeGcMP6xyZaR29EpbCxKrG0SRIZNpsx3nJWXJcZNXw "Attache – Try It Online") Set to `f` and call as `f[function, array]`.
## Explanation
This is a fork of two functions: `Fold` and `/Diagonal`. This, for arguments `f` and `a`, is equivalent to:
```
Fold[f, (/Diagonal)[f, a]]
```
`/`, when applied monadically to a function, returns a function that is applied to its last argument. So, this is equivalent to:
```
Fold[f, Diagonal[a]]
```
This folds the function `f` over the main diagonal of `a`.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 77 bytes
```
func z(F,M,r){for(e=1;e<M[1]&&e<M[2];)r=@F(r==""?M[1,1]:r,M[++e,e])
return r}
```
[Try it online!](https://tio.run/##bZNdb5swFIbv/Ss8qlVQHDXYXNWxWlVap12w60kVq1BKNlI@IgcKLMpvz3xscFLoDee1n@P3HMucpH07bZpyjXd5s3c70nsHhLFM60aWuPN7dEQaF1n5CV9YXmdFOuc3lu@qNpUz/tvyfVO80Cl3VQPeLR1zOtrPO6TnGkXSzfiqv@/vOttlW/2aptAbi/@sXy1t/2Z56vZfxFIvMa5Fz7XoRYe/4mHRiRrE8aIkH@3ydWHtso26jVBmY9qSX97zdizt6etgbB7ln/tEIiK9w6aSbioCnq6i5yC@voZIY@5J8fDkSiEc514BEsR3kkTPvp@SNPbQYC@Pp8dv33/8PKAoUKeF@tJYMHwFXljgsimwrNo9wWA6bKyrvCnKPYLK3PezldCHuQcbW7FUe9uVseKeChnZxsL335OcI/VRCQhFFMpRriIU1F6Z0Lt@wHG2WEztqLGjM7sA7BjYMa7ihd1y6I590h0zduyDHYpC8Am5itoH1sQ0CopaxUABphZTiylgpjGzmAFmRlkckrFcCHhQDBRCO5mVNXb0/AhHvbiRjnqMwOMj1uNjsJYTrKfTYC0B0zOG4areU/lCTY4eNshh5xw1Sb2hasym9kk3mCfdBNGBwGSNaGTq/zdQCWAhsCM6/Qc "AWK – Try It Online")
I was curious if `AWK` could do functional programming at all. I think this counts. 
The "Matrix" is defined as a standard associative array, with extra fields `M[1]=#rows` and `M[2]=#columns`. The function name is passed in as a string which is evaluated via the `@F(...)` syntax. Evaluation is performed left to right.
The `r` parameter is a placeholder to prevent overwriting an existing `r` variable and to avoid the need to reinitialize for each call. Typically extra space is added to designate such placeholders in `AWK`, but this is code golf, so every byte counts. :)
The TIO link implements all the test cases.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 10 bytes
Folds from right-to-left  
Saved 5 bytes using a new built-in as suggested by *Kevin Cruijssen*
```
Å\`[.g#I.V
```
**Explanation**
Works the same as the old version, except that `Å\` is a new built-in for pushing the main diagonal.
[Try it online!](https://tio.run/##yy9OTMpM/f//cGtMQrReurKnXtj//9HRhjpGOsaxOtEmOqY6ZkDaXMdCxzI2luvQdm0A "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##yy9OTMpM/W/hFvr/cGtMQrReunKEXtj/Wp3/WlzR0YY6RjrGsTrRJjqmOmZA2lzHQscyNpYrF4@cLlAOJgZRE8ulbQ0UBDJ1TICCQCkdcyANVK5jaACUPbRdG495jxpmVZ/bgUdBzKHt@LXrHdoPth4IgRJGUIUg50A0AGFsLAA)
**Old Version**
```
¬g£vyNè}[.g#I.V
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0Jr0Q4vLKv0Or6iN1ktX9tQL@/8/OtpQx0jHOFYn2kTHVMcMSJvrWOhYxsZyHdquDQA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##MzBNTDJM/V9jdHhLWWVC6P9Da9IPLS6r9Du8ojZaL105Qi/sf63O/@hoQx0jHeNYnWgTHVMdMyBtrmOhYxkby6XFhVsuFygHE4OoieXSBYoBWTomQDGgjI45kAaq1jE0AEpqW@Mx7dB2bTyyjxpmVZ/bgUdBzKHtYKuBEChqBFUFcgpENRBCjNE7tB8A)
**Explanation**
```
¬                 # get the head of the input (first row)
 g                # get its length (number of columns)
  £               # take that many rows from input
   v              # for each row_index, row (N,y) do:
    y             # push the row
     Nè           # get the nth element of the row
       }          # end loop
        [.g#      # loop until one value remain on the stack
            I.V   # run the input function
```
[Answer]
# Java 8, ~~88~~ ~~81~~ ~~70~~ 69 bytes
```
m->{try{for(int i=1;;m[0][0]=f(m[0][0],m[i][i++]));}finally{return;}}
```
Puts the result in the very first cell of the matrix instead of returning an integer (to save a byte).
[Try it online.](https://tio.run/##7ZXfT4MwEMff91f0xQRchw5/i1MTn40P843w0HVFO6GQUiYN6d8@W8qmRqYvM8HEQArcHdf7fnIcC7REoywnbDF/WeEEFQW4R5TVAwDQrBAcYQEKgQTFwHofSSGMFwDKBIgds1bQrNK1dgA4ESVnoBrKoLGoZm2WvJwlOtdCb@uVgiZeXDIsaMa8u4wVZUr4lc4VRmF0DTCYrNLRdS24rOOMN1vRyTgI0vAw0uckdto7mIY0CulwGLluoGLKUJLI2pYRKLUyO5tSTCGDTRGtrmVG5yDVop2p4JQ9hRFyNwpNJfqal@IeaW8FJoCR17VnLXhjqsfQh0cKfrEfwxN42mE/g@fwwvJRFpbxGcjOBuftw5JwTuekfd4O/h39fot@DV952EMYk1w4H9S4NmgqC0FSLyuFl2sCImEfgyziNrTl8td4GK@rK3728uzVqaB0@4FnGwaLbfdtMepJW2h18LhDt6YBzzrsuing@PAX@kLPKPfA//9WPo1t/396fCLSDI4UVT0aHD0h4@9XfRko@ujQ7W/hZAZQNz997J5TgtOO5rGvGt8PP3NHHjzheZOhM4VxfptCXo1vqksTJmG19ztNrAZq9QY)
Both folds `[[1,2,3],[4,5,6],[7,8,9]]` to `f(f(1,5),9)`.
-7 bytes indirectly thanks to *@KamilDrakari* by using a similar trick as he did in [his C# answer](https://codegolf.stackexchange.com/a/154011/52210): instead of having a maximum boundary for the loop based on the rows/columns, simply try-catch the `ArrayIndexOutOfBoundsException`.  
-11 bytes replacing `catch(Exception e)` with `finally`.  
**Explanation:**
```
m->{                   // Method with integer-matrix parameter and no return-type
  try{for(int i=1;     //  Start the index at 1 (0-based indexing)
          ;)           //   Loop indefinitely:
    m[0][0]=           //    Replace the value in the first cell with:
     f(m[0][0],        //     Call f with the current value of the first cell
       m[i][i++]));}   //     and the next diagonal cell as arguments
  finally{             //  If an ArrayIndexOutOfBoundsException occurred we're done,
    return;}}          //   in which case we'll terminate the method
```
**Black box input format:**
Assumes a named function `int f(int x,int y)` is present, which is allowed [according to this meta answer](https://codegolf.meta.stackexchange.com/a/13707/52210).
I have an abstract class `Test` containing the default function `f(x,y)`, as well as the lambda above:
```
abstract class Test{
  int f(int x,int y){
    return x+y;
  }
  public java.util.function.Consumer<int[][]> c =
    m->{try{for(int i=1;;m[0][0]=f(m[0][0],m[i][i++]));}finally{return;}}
  ;
}
```
For the test cases, I overwrite this function `f`. For example, the first test case is called like this:
```
int[][] inputMatrix = new int[][]{
  new int[]{1,2,3},
  new int[]{4,5,6},
  new int[]{7,8,9}
};
new Test(){
  @Override
  int f(int x,int y){
    return x*y;
  }
}.c.accept(inputMatrix);
System.out.println(inputMatrix[0][0]);
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 86 bytes
```
T	I =1
	T =M<1,1>
I	I =I + 1
	T =EVAL(F '(T,M<I,I>)')	:S(I)F(RETURN)
	DEFINE('T(M,F)')
```
[Try it online!](https://tio.run/##PZDPC4MgFIDP@ld468m8lO1XVFCkIKw2TAe77jzWYf8/7Zlzh4Tv8wPf6/NensurXEkFA18dMazJKXGsGetc5C01wRi2Y9Gqe3cBzTJwYqyNMC3POKlmMFyDVc7bidOBDEqbSUHmYBQai/VvZj9CJ3p0lHTWsgaP7gGZFPKntme3ISIUCEUCiSAjFFtWJgjZPkHIDhHklh0ThOyUIGRnSq7e3Tzu5gC1CCOGnUBNA6cIBD@cE39BjzYtibfrFw "SNOBOL4 (CSNOBOL4) – Try It Online")
Defines a function `T` (for `TRACE`) that takes an `ARRAY` and a string `F` that's the name of a function. Folds left-to-right.
Using indirect reference (`$`) doesn't work with functions. So using `EVAL` and passing a string to the name seems to be the only way to get a black-box function in SNOBOL.
Also, it's quite painful to define arrays; however, because invalid array references cause `FAILURE`, this works for non-square arrays -- if `I` is out-of-bounds in either dimension, the `F(RETURN)` forces the function to return.
### Edit:
Possibly, based on [this meta post](https://codegolf.meta.stackexchange.com/a/13707/67312), I may assume that the black-box function `F` is defined under the name `F`, which would drop this to 75 bytes (remove use of `EVAL` and `,F` in the function definition). However, I prefer this version since it's closer to passing a reference to a function.
[Answer]
# C, 76 bytes
```
i,t;f(g,A,n,m)int*A,(*g)();{for(t=*A,i=m+1;--n*--m;t=g(t,*A))A+=i;return t;}
```
Left-to-right.
[Try it online!](https://tio.run/##jZLNbqMwEMfveYpRo1Y2jNViPluLVhyaF9jeunuo0oAs1W6VUgmU5tWbDrAJpOyiYAbw378ZD@NZimK53M2fV7m2K1gwzUHbEvL5XDP6wGbG1WzBPL5gkswnC8hCsogsJkv4TmOpclZghhYNJycnQ@YUnHG1yV/XrExJ0KlxPSWEdYQwqkwLVqKTcZ65qVbrVfmxtlCq7SGdh/tfD0wjWATD4W1NYXN2dv78254h5OyiyRIha58tQ5nOmvTNk7aMzzYzoKsRMu/xD6Sw8VCijwGGGGGMCV5vVc/IExi/Y7rVlhyuBt3qD3/0roZQeMI20QlMfAKT7BPaD7@1hqdBZIu2dfYQfLp5r8iRQlN5rAQjJhwp0UiJR0qCELTKtjvB3GvaD6q2AaHen@XfJqmcWh1I@U@ymdiuEtR/wGxaKaiFUN2mzWXBSaFSw8C2D@tPJiAGCQRTJKvcmsMlyJ4PJyODC3L4e9EkfVvDHfncwMAjnvKQTtWTyX9LZ6htjoIfCqnAnFfw@UmvWoHrGn5UQUPRd1/L/OWpeN@JF/MN)
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 79 bytes
```
(load library
(d D(q((M)(i(h M)(c(h(h M))(D(map t(t M))))(
(q((F M)(foldl F(D M
```
The last line is an unnamed lambda function that takes a function and matrix and returns the matrix trace. The trace is left-associative (i.e. `f(f(1,5),9)`). [Try it online!](https://tio.run/##jY/LTsMwEEX3/Yq7Y6IuoKFQ2EfddZcfcBOHWPIjTRzqfH06zgMQEqirmfE5uuPxyg5adc04knaihFbnVrTDhkpkdCE6JaSoBpeC6qlJKCMjGnjyceI5ynmUj9GrnC41jpThNFLhjJHWI5OVshIyCNNoiaq3hVfOdvC18BCttA8eyvIo1y8kMVZ8foAuIAoYEtAjaIupTePmaIRtOvxUJs7dgtPwG4YJbSiH6XU60x1SPDPf4wWvXA94w/sckaNx1zusrj8vYSue9QV/HcJv2DNlBweuHIHd06p9X/PvMiPCPT9fj/9TGm8 "tinylisp – Try It Online")
### Ungolfed
We define a helper function to compute the diagonal; then `generalized-trace` is merely a small wrapper around the library function `foldl`.
```
(load library)
(def diagonal
 (lambda (matrix)
  (if (head matrix)
   (cons
    (head (head matrix))
    (diagonal (map tail (tail matrix))))
   nil)))
(def generalized-trace
 (lambda (func matrix)
  (foldl func (diagonal matrix))))
```
When computing the diagonal recursively, we check whether `(head matrix)` is truthy. If the matrix is out of rows, it will be the empty list (nil), and `head` of nil is nil--falsey. Or, if the matrix is out of columns, its first row (head) will be the empty list (nil)--falsey. Otherwise, there will be a nonempty first row, which is truthy.
So, if the first row doesn't exist or is empty, we return nil. Otherwise, if there is a nonempty first row, we take `(head (head matrix))`--the first element of the first row--and `cons` (prepend) it to the result of the recursive call. The argument to the recursive call is `(map tail (tail matrix))`--that is, take all rows but the first, and take all but the first element of each row.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes
```
f->a->fold(f,[a[i,i]|i<-[1..min(#a,#a~)]])
```
[Try it online!](https://tio.run/##jZDRCsIwDEV/pbiX1qXq6nRKdT9SKhRlo7DNIj60IP76TCci@rIRCEnuySXEmZvltetrciR9xUvDy@raXGgFyigLVj/sgatssWhtRxMDiXkyrVlvnGsC9YSXxN1sd8dyFpsZqalXmWaYhWYMiFLUQ2BR9POAfQYC1jKHDWxlATvYa43TL3SaAvEIveUB/ZWpTwNbChyhBLlEDAqJLpCt/oxSMeWo1vihHifF3I9Dzbn92AkkhRQDH4@NWxg6PvkF "Pari/GP – Try It Online")
[Answer]
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~72~~ ~~69~~ 60 bytes
```
m=>{try{for(int i=1;;m[0][0]=f(m[0][0],m[i][i++]));}catch{}}
```
[Try it online!](https://tio.run/##vVNdT4MwFH0ev6KPMOo@cDpNB4kx8cklJj74QHiotWxNRllot0FIf/u8wFiGOn2aFFruxzkXbu5h6ooptt8oIRfotVCaJ8SSNOFqTRlH6zVblBZbUaWQzsCTlZbSVAuGnjaSzYTU@PAEKCZt7IFpkcoqGkZhFDRQ5KN94gelzooyTjMbokj4Y0KScBTB7cf24Q0noYhC4bqR4xDDqGbL0pg9sdab9xXQH6psU/GB5lRI2ymtLc1QQnUmGFdQSfJdGJUW@nI17mYfYw9fG9wYE3yDb1tjiu/wvTH4kvAOouH6AwEpeNIiAIynrQHl8Hh04Q/@f/hw2P19WC3GO2WrGnNCDcuYDpkhVsc@ji5qtyCMUAxeGJ1O5vcJsnNcOH6Q9wt8LlZNtjOnejl4SXe172xqfvULTe4WztA7j3Vtr/8Td116TvOzSK@f/9TtFUsQSz84WvKMf2tg76hZkNeIwDFDUzhcF9TX68XgrTsI0iVg15K3W0WC06m8j6lU6YoP3jKh@bOQnYxG/FWeseq1/wQ "C# (Visual C# Compiler) – Try It Online")
`try/catch` allows the diagonal to be correctly reached by simply going along it and terminating when out of bounds.
3 bytes saved because, as pointed out by Kevin Cruijssen, [black-box functions can be assumed to exist under a specific name](https://codegolf.meta.stackexchange.com/a/13707/71434).
9 bytes saved by returning via [modifying an argument](https://codegolf.meta.stackexchange.com/a/4942/71434).
Thus, the function is called by storing the desired function under the name `f`, calling `trace(matrix)`, and the result is stored in `matrix[0][0]`.
Alternatively, if you really like verbosity,
# [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~97 + 13 = 110~~ ~~78~~ 69 bytes
```
(int[][]m)=>{try{for(int i=1;;m[0][0]=f(m[0][0],m[i][i++]));}catch{}}
```
[Try it online!](https://tio.run/##vVPfb4IwEH6Wv6KPIPUXc3NL1WRZsqeZLNnDHggPXS3aRIqhVSGkf7s7QIxM3Z4cBy339b47uNzHVIcptt8oIRfoI1OaR8SSNOJqTRlH6zVb5BZbUaWQTgBJcktpqgVDrxvJxkJqfHimKCT12TPTIpbFqR/4wbSiogna2wcocibTXCdZHsZJgSExGRAS@f0A7kloH95w5IvAF64bOA4xjGq2zI3ZE2u9@VpBnUO5bSzmaEaFtJ3c2tIERVQngnEFJSXf@UFuoR9XBVfrAHv4zuDKGeJ7/FA7I/yIn4zBt6Q3GFWuPxgQgoc1A8h4VDtQDg/6N/7g/6f3es3fB6s53mm2ojEnqcGMaSQzxGr4xxlG9TL1AxQCCqPTiDyfIDvFGUxx2s7wtbNisp0Z1cvue7wrsauhaeeXNKmbOT3vOte1vfal3GXpGU2vMr12eqnbKxYhFs85WvKEnzWwddQsyKtPYBujEWyuC@prtUJAyw6CdAn4pfbtWpEAOgX6EksVr3j3MxGavwnZiKjEX8QZq7T9Nw "C# (Visual C# Compiler) – Try It Online")
32 bytes saved by using a predefined function, because not taking the function as a parameter allowed removing the `System` import and the long `Func` generic type.
[Answer]
# JavaScript, ~~61~~ ~~57~~ ~~56~~ ~~52~~ ~~50~~ ~~44~~ 42 bytes
Reduces left to right. Assumes the function is assigned to variable `f`, as per [this meta post](https://codegolf.meta.stackexchange.com/a/13707/58974) brought to my attention by Mr. Xcoder & totallyhuman. Can't say as I agree with it as it directly contradicts our existing consensus that we may not assume input is assigned to a pre-defined variable, but I'll take the few bytes saving for now.
```
a=>a.map((y,z)=>x=(n=y[z])?z?f(x,n):n:x)|x
```
---
## Test Cases
```
g=
a=>a.map((y,z)=>x=(n=y[z])?z?f(x,n):n:x)|x
o.innerHTML=[[`f(x,y) = xy`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>x*y,45],[`f(x,y) = x<sup>y</sup>`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>x**y,1],[`f(x,y) = x-y`,[[4,5,6],[1,2,3]],(x,y)=>x-y,2],[`f(x,y) = <sup>(x+y)</sup>⁄<sub>2</sub>`,[[2,3,4],[5,6,7],[8,9,10]],(x,y)=>(x+y)/2,7],[`f(x,y) = x+2y`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>x+2*y,29],[`f(x,y) = max(x,y)`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>Math.max(x,y),9],[`f(x,y) = 2x`,[[1,2,3],[4,5,6],[7,8,9]],(x,y)=>2*x,4],[`f(x,y) = lcm(x,y)`,[[2,2,2],[2,2,3],[2,3,3],[4,4,4]],(x,y)=>-~[...Array(x*y).keys()].find(z=>!(++z%x|z%y)),6]].map(([a,b,c,d],e)=>`Test #${++e}:  ${a}\nMatrix:   ${JSON.stringify(b)}\nFunction: ${f=c}\nResult:   ${g(b)}\nExpected: ${d}`).join`\n\n`
```
```
<pre id=o></pre>
```
[Answer]
# APL NARS, 20 bytes, 10 chars
```
{⍺⍺/1 1⍉⍵}
```
test:
```
  f←{⍺⍺/1 1⍉⍵}
  ⎕←q←3 3⍴⍳10    
1 2 3
4 5 6
7 8 9
  ×f q
45
  *f q
1
  {⍺+2×⍵}f q
47
  ⌈f q
9
  {2×⍺+0×⍵}f q
2
  -f ⊃(4 5 6)(1 2 3)
2
  {(⍺+⍵)÷2}f ⊃(2 3 4)(5 6 7)(8 9 10)
5
  ∧f ⊃(2 2 2)(2 2 3)(2 3 3)(4 4 4)
6
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~55~~ 53 bytes
```
->f,m,n=m[i=0][0]{(k=m[i+=1]&.[]i)?(n=f[n,k];redo):n}
```
[Try it online!](https://tio.run/##ndFRT8IwEAfwdz9FUxKzstvc6sZEM/wg5z2gAiG4YSYkbZZ99nl1gJD0Ae0lvfTll/9dm/2r7VdlH82WUEFdVrguE8KE2mDjHmGZ0m2MtFbPQV0usYYNPTWL9616rLv@c7/7EnLUrlBEMwO2NWPbgRgOYgoa7gkwgxwm3At4gCmRoE6K45EvuyDLlbzxWL/Y9VbqpaLzWEdiIC@Jc0r7qMCEVt3pHw6RAciYYhAK7pwJ0uTSdFQuto0ovNFCfRrzDxsrHKinPhH5oriaG1avF72UHpt/fKd22TLvsPHHWyXsaXlc7OiD65Y5@FwH13kTJftv "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
Left-to-right.
```
ŒDḢç/
```
[Try it online!](https://tio.run/##y0rNyan8f3hZzv@jk1we7lh0eLn@////o6ONdIAwVgdMG4NpYzBtogOEsbEA "Jelly – Try It Online")
**Disclaimer:** I do not know if this an acceptable input method for black-box functions. This assumes that the function is implemented in the link above, and is thus "named" (that is, it's callable with) `ç`, but otherwise I have no way to assign it to `ç`. If anyone has more experience with Jelly + black box functions, I would appreciate thoughts. After spending some time in chat, we [figured](https://chat.stackexchange.com/transcript/message/42464622#42464622) that using `ç` might indeed be valid. 
[Answer]
## Clojure, 30 bytes
```
#(reduce %2(map nth %(range)))
```
Reduces "from the left".
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
F₁►L∂↔
```
[Try it online!](https://tio.run/##yygtzv7/3@1RU@Ojabt8HnU0PWqb8l/fSPv//@hoIx1jHZNYnWhTHTMdcyBtoWOpY2gQGwsA "Husk – Try It Online")
takes function in the footer.
Folds from the left.
]