title: Implement an Over function

text:
# Question
Title: Implement an Over function
Over is a higher-order function in multiple languages such as APL (). It takes 2 functions and 2 values as arguments, applies the first function to both values, then applies the second to their result. For example, using  to represent Over:

```
1 ²⍥+ 2

```

We would first calculate `²` of each argument: `1² = 1` and `2² = 4`. We then apply `+` to these, yielding `5`.

You are to take as input:

* A black box function, \\$f\\$, which takes an integer as input and returns an integer
* A black box function, \\$g\\$, which takes 2 integers as input and returns a single integer
* 2 integers, \\$a\\$ and \\$b\\$.

You should then return the result of \\$g(f(a), f(b))\\$.

If you have a builtin specifically for this (e.g. APL's , Husk's `¤` etc.), consider including a non-builtin answer as well. It might even get you an upvote :)

You may input and output in the most convenient format for your language, and in any convenient method, **including taking \\$a\\$ and \\$b\\$ as a pair/list/tuple** `[a, b]`

For the sake of simplicity, you can assume that the black-box function will always input and output integers within your language's integer domain, and that \\$a\\$, \\$b\\$ and the output will be with your language's integer domain.

This is , so the shortest code in bytes wins

## Test cases

```
f
g
a, b -> out

f(x) = x²
g(x,y) = x - y
-2, 2 -> 0

f(x) = φ(x)     (Euler totient function)
g(x,y) = 2x + y
5, 9 -> 14

f(x) = x³-x²-x-1
g(x,y) = y⁴-x³-y²-x
-1, -1 -> 22

f(x) = x
g(x,y) = x / y   (Integer division)
-25, 5 -> -5

```

# Answer
> 25 votes
# Haskell, 12 bytes

```
f?g=(.f).g.f

```

Try it online!

Haskell was made for this.

Let's unpack it:

```
(f?g) x y =
(((.f).g.f) x) y =
(.f)(g (f x)) y =
((g (f x)).f) y =
g (f x) (f y)

```

If you're wondering what happens if we make this further pointfree in `f` and `g`, we can express `(?)` as:

```
\f->((.f).).(.f)
(.).(.).flip(.)<*>flip(.)

```

The flipped version of `?` that's invoked as `g?f` is a little nicer:

```
((.).flip(.)<*>).(.)

```

(I used pointfree.io for these.)

*Test cases copied from Unrelated String.*

---

## Haskell, 10 bytes

```
(.map).(.)

```

Try it online!

If the input `[x,y]` is a two-element list, and the binary function `g` accepts its two arguments as such a list. The main function takes is arguments as `g` then \`f.

# Answer
> 11 votes
# Factor, 16 bytes

```
[ bi@ rot call ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes a quotation with stack effect `( x x -- x )`, two integers, and a quotation with stack effect `( x -- x )` on the data stack as input. It takes them in that order, as that allows for what I believe is the shortest code. Assuming the data stack looks like `[ + ] 1 2 [ sq ]` when this quotation is called...

* `bi@` Apply a quotation to two objects.

**Stack:** `[ + ] 1 4`
* `rot` Move the object third from the top to the top.

**Stack:** `1 4 [ + ]`
* `call` Call a quotation.

**Stack:** `5`

# Factor, 10 bytes

```
map-reduce

```

Try it online!

Built-in.

# Answer
> 9 votes
# , 12 bytes

```
2 :'(u v)~v'

```

Try it online!

Non-built-in solution. This is an explicit conjunction that takes two functions on two sides and evaluates to a train that acts like "u over v", but with flipped arguments.

```
x ((u v)~v) y
x (u v)~ v y
(v y) (u v) x
(v y) u v x

```

# , 1 byte

```
&

```

Try it online!

J's built-in conjunctions can be assigned to a variable, unlike in Dyalog APL.

# Answer
> 8 votes
# JavaScript (ES6), 23 bytes

```
(f,g,x,y)=>g(f(x),f(y))

```

Try it online!

# Answer
> 7 votes
# Haskell, ~~17~~ ~~16~~ 15 bytes

```
(f!k)x=k(f x).f

```

Try it online!

*-1 thanks to Wheat Wizard repatterning the use of infix*

# Answer
> 7 votes
# Rust, 21 bytes

```
|f,g,x,y|g(f(x),f(y))

```

Try it online!

An anonymous function that has the signature

```
fn(fn(i32)->i32,fn(i32,i32)->i32,i32,i32)->i32

```

Don't you love it when the function signature is twice as long as the function itself?

# Answer
> 6 votes
# APL (Dyalog Classic), 9 bytes

```
{⍺⍺/⍵⍵¨⍵}

```

```
{⍺⍺/⍵⍵¨⍵}
 ⍺⍺          left operand (function argument)
   /         reduce
    ⍵⍵       right operand
      ¨      each
       ⍵     right argument

```

APL has a builtin for this, ⍥, but here's a non builtin solution as an operator taking an array of arguments.

Alternative 'proper' definition: `{(⍵⍵⍺)⍺⍺⍵⍵⍵}`, or more readably as `{(⍵⍵ ⍺) ⍺⍺ ⍵⍵ ⍵}`

Try it online!

# Answer
> 6 votes
# Racket, 26 bytes

```
(λ(f g x y)(g(f x)(f y)))

```

Try it online!

`λ` is 2 bytes, BTW.

Pretty self-explanatory, but:

```
(λ(f g x y)(g(f x)(f y)))  Anonymous function submission
(λ                      )  Lambda;
  (f g x y)                accept functions f, g and arguments x, y and return
           (g          )   g(
             (f x)           f(x),
                  (f y)            f(y))

```

# Answer
> 6 votes
# , 29 bytes

```
function(f,g,a,b)g(f(a),f(b))

```

Try it online!

No surprises here. In a future version of R, `function` will be replaceable with `\` (which is supposed to look like a lambda).

# Answer
> 6 votes
# Wolfram Language (Mathematica), 10 bytes

```
#2@@#/@#3&

```

Try it online!

Input `[f, g, {x, y}]`.

# Answer
> 5 votes
## SKI-calculus, 71 bytes

```
S(S(KS)(S(K(S(KS)))(S(K(S(K(S(KS)))))(S(K(S(K(S(KK)))))(S(KS)K)))))(KK)

```

Edit: Another go at hand-translating the lambda calculus expression into SKI using the rules in Wikipedia, this time arriving at the same answer as @Bubbler.

# Answer
> 5 votes
# tinylisp, 23 bytes

```
(q((f g x y)(g(f x)(f y

```

Try it online!

## Ungolfed

```
(lambda (f g x y)     ; a lambda function taking four arguments
  (g (f x) (f y)))    ; apply f to x, f to y, and g to the results

```

# Answer
> 4 votes
# C (clang), <sup>~~54~~ \\$\cdots\\$ ~~37~~</sup> 36 bytes

```
o(f(),g(),a,b){return g(f(a),f(b));}

```

Try it online!

*Saved 8 bytes thanks to dingledooper!!!*
*Saved 2 bytes thanks to ceilingcat!!!*
*Saved a byte thanks to jdt!!!*

# Answer
> 4 votes
# Python 2, 25 bytes

\\$ a \\$ and \\$ b \\$ are inputted as a tuple (called \\$ x \\$).

```
lambda f,g,x:g(*map(f,x))

```

Try it online!

# Answer
> 4 votes
# Jelly, 4 bytes

```
Ñ€ç/

```

Try it online!

Takes `f` on the first line, `g` on the second line, and the code is on the third line (this is standard for Jelly). Also, takes the arguments together as a list

```
 €    For each of the arguments
Ñ     Apply the next link (wraps around to `f`)
   /  Reduce by (for a pair, applies dyad to the first and second element of the list)
  ç   Apply the last link (`g`)

```

Also works:

# Jelly, 4 bytes

```
ÑçÑ}

```

Try it online!

```
Ñ     Apply `f` (to the left argument, since it's called as a monad)
 çÑ}  2-2 chain - given dyads x, y, computes x(a, y(a, b)) if the chain's current value is a and the right argument is b
 ç    Apply `g` to the current value (f(left)) and
  Ñ}  A dyad formed from a monad by ignoring the left argument

```

Basically, `Ñ}` is `(l, r) -> f(r)`, so this ends up evaluating as `λ x y -> g(f(x), (λ a b -> f(b))(x, y))` which simplifies to `λ x y -> g(f(x), f(y))` as required.

(These chaining rules are absolutely beautiful. Thank you Dennis for Jelly :P)

# Answer
> 4 votes
# Scala, 16 bytes

```
_ map _ reduce _

```

Try it online!

Takes (\[a,b\],f,g). There’s more ways to do this but I’m on mobile so I’ll add them later

# Answer
> 4 votes
# Proton, 21 bytes

```
(f,g,a)=>g(*map(f,a))

```

Try it online!

Time to bring out this garbage again :D

# Answer
> 4 votes
# Stax, 7 bytes

```
n!aa!a!

```

Run and debug it

A full program which can be executed as a block as well.

accepts the arguments as `g x f y`.

# Answer
> 4 votes
# Ruby, 23 bytes

```
->f,g,x,y{g[f[x],f[y]]}

```

Try it online!

Or:

# Ruby, 23 bytes

```
->f,g,*x{g[*x.map(&f)]}

```

Try it online!

# Answer
> 3 votes
# Vyxal, ~~8~~ 3 bytes

```
M$R

```

Try it Online!

Takes `[g, [a, b], f]`. If reduction was reversible, then this would be 2 bytes.

## Explained

```
M$R
M   # map f over [a, b]
 $R # reduce that by g

```

# Answer
> 3 votes
# Excel (Insider Beta), 29 bytes

```
=LAMBDA(f,g,a,b,g(f(a),f(b)))

```

`LAMBDA` is only available through Excel Insider Beta. The functions have to be defined as names to work. In my case, I defined a name q that is equal to the above and then used the formula `=q(LAMBDA(x,x^2),LAMBDA(x,y,x+y),1,2)` in a cell. This could also be done by defining the names `a=LAMBDA(x,x^2)` and `b=LAMBDA(x,y,x+y)` and then use the formula `q(a,b,1,5)`.

# Answer
> 3 votes
# Coconut, 11 bytes

Takes input as `Ꙫ(g)(f, [a, b])`.

```
g->g<*..map

```

Try it online!

`<*..` is the *multi-arg backward function composition*, which makes this function equivalent to

```
g->*args->g(*map(*args))

```

# Answer
> 3 votes
# Husk, ~~5~~ 4 bytes

```
₂₁⁰₁

```

Try it online!

Black-box functions are supplied as sequential lines in the code (in the footer in the TIO link), input values are given as program arguments.

```
₂₁⁰₁     # 2 argument function: second argument is implicit
   ₁     # perform function ₁ using second argument
 ₁⁰      # perform function ₁ using first argument
₂        # perform function ₂ using the last 2 values as arguments

```

# Answer
> 3 votes
# Red, 24 bytes

```
func[f g x y][g f x f y]

```

Try it online!

This version doesn't work in TIO (Red is not up-to date), that's why I provide a screenshot from my Red GUI console:

# TIO compatible version, 28 bytes

```
func[f g x y][do[g f x f y]]

```

Try it online!

# Answer
> 3 votes
# Julia, ~~17~~ 16 bytes

```
F(!,+,a,b)=!a+!b

```

Try it online!

**Previous answer, 17 bytes**

```
g*f*x=g(f.(x)...)

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), 5 bytes (SBCS)

Full program version of rak1507's implementation.

```
⎕/⎕¨⎕

```

Try it online!

# Answer
> 2 votes
# Attache, 10 bytes

```
${z|x|>&y}

```

Try it online!

Takes input as `F[f, g, [a, b]]`, where `F` is the above function.

This is two separate pipes: The vectorizing pipe `|`, and the regular pipe `|>`. `z|x` pipes each element of `z` into the unary function `x`, i.e., `Map[x, z]`. Then, this array is piped to `&y`, which passes each element of the array as a separate parameter.

## Alternatives

`${&y!x=>z}`, 10 bytes. Same input as above.

`{_2@@Map[_]}`, 12 bytes. Takes parameters `f` and `g`, returns a function which takes a tuple `[a, b]` as input.

# Attache (builtin), 3 bytes

```
`#:

```

Try it online!

Simple quote-operator. Called as `(`#:)[g, f][a, b]`.

# Answer
> 2 votes
# Stacked, 11 bytes

```
[@:g"!...g]

```

Try it online!

Simple anonymous function. Takes input on stack as `(a b) f g`.

Works by storing `g` as a temporary function variable. Then, applies the `"` transformation on function `f`, which makes it apply on each element its called on. `!` calls this function `f"` on the tuple `(a b)`. Then, we simply put these two elements on the stack and call `g`.

# Answer
> 2 votes
# C (gcc), 30 bytes

```
#define o(f,g,a,b)g(f(a),f(b))

```

Try it online!

# Answer
> 2 votes
# Standard ML, 24 bytes

```
fn(f,g,a,b)=>g(f a)(f b)

```

---

<sub>

### Concurr pre-release, 50 bytes

```
$lambda\f:lambda\g:lambda\a:lambda\b::g(:f a)$:f b

```

Wow that's horrible.

</sub>

# Answer
> 2 votes
# Japt, ~~6~~ 5 bytes

As far as I know, Japt does not support taking functions as inputs, or at least I couldn't find a way that actually works. To sidestep this problem, I've moved the blackbox functions into the code header while excluding them from the byte count. Their definition or form is not important for the implementation itself. Hope this is valid, otherwise I don't think Japt can compete.

The functions are to be stored in `V` and `W` respectively.

```
mV rW
mV    // Map the array of input numbers through V
   rW // then reduce the result with W.

```

Shaved off a byte thanks to Shaggy by taking the input as an array instead.

Try it online!

# Answer
> 2 votes
# CJam, 4 bytes

```
q~%*

```

Inputs are: function *g*; array of numbers; function *f*. Functions are defined as code blocks.

Try it online! Or verify all test cases: , , , .

### Explanation

```
q   e# Read all input as an unevaluated string
~   e# Evaluate. Pushes a code block, an array, and a code block to the stack
%   e# Map (second function over the array)
*   e# Reduce (the array using the first function)
    e# Print (implicitly)

```

# Answer
> 2 votes
# Raku, 17 bytes

```
{&^g(|@^x».&^f)}

```

Try it online!

`&^f` and `&^g` are the function arguments to the over function, and `@^x` is the list of arguments to `f`. `@^x».&^f` maps the arguments to `f` over `f`, and `|` flattens that list into the arguments to `g`.

# Answer
> 2 votes
# Clojure, ~~17~~ 16 bytes

```
#(%(%2%3)(%2%4))

```

Try it online!

Takes inputs in the order of \\$g, f, a, b\\$.

# Answer
> 2 votes
# Racket, 30 bytes

```
(λ(f g x)(apply g (map f x)))

```

Try it online! Takes a and b as a list i.e. `'(a b)`.

# Answer
> 2 votes
# Lua, 41 bytes

```
function k(f,g,x,y)return g(f(x),f(y))end

```

Try it online!

# Answer
> 2 votes
# MMIX, 32 bytes (8 instrs)

Takes arguments `f`,`g`,`x`,`y`.

(jxd)

```
00000000: fe040004 c1070200 bf060000 c1080300  “¥¡¥Ḋ¬£¡Ḃ©¡¡Ḋ®¤¡
00000010: bf070000 bf050100 f6040004 f8060000  Ḃ¬¡¡Ḃ¦¢¡ẇ¥¡¥ẏ©¡¡

```

Disassembly:

```
on  GET    $4,rJ
    SET    $7,$2
    PUSHGO $6,$0    // $6 = f(x)
    SET    $8,$3
    PUSHGO $7,$0    // $7 = f(y)
    PUSHGO $5,$1    // $5 = g($6,$7)
    PUT    rJ,$4
    POP    6,0      // return $5,f,g,x,y,$4

```

# Answer
> 2 votes
# PPL v1.0.11, 31 bytes

```
fnv(f,g,x,y){
returng(f(x,y))
}

```

This must be run on PPL version 1.0.11 (or later) because the ability to pass functions as parameters was only added in v1.0.11. Fairly simple, if you can get past the unreadability of the "mashing tokens together".

# Answer
> 2 votes
# Java (JDK), 30 bytes

```
(f,g,x,y)->g.a(f.a(x),f.a(y));

```

Try it online!

# Answer
> 2 votes
# Python, 27 bytes

```
lambda f,g,a,b:g(f(a),f(b))

```

# Answer
> 2 votes
# Fig, \\$2\log\_{256}(96)\approx\\$ 1.646 bytes

```
RM

```

See the README to see how to run this

The perfect job for a functional language. Here is an example program with \\$a = 1\\$, \\$b = 2\\$, \\$f(x) = -x\\$, \\$g(x, y) = x - y\\$, producing the correct result of `1`:

```
RMw1 2'Nx'-

```

Explanation:

```
RM # Takes input as [a, b], f, g
 M # Map the input with the first function
R  # Reduce the result by the second function

```

# Answer
> 2 votes
# Arturo, 21 bytes

```
$[f g x y][g f x f y]

```

Try it

# Answer
> 1 votes
# Python 2, 37 bytes

```
lambda f,g,a,b:reduce(g,map(f,[a,b]))

```

Try it online!

Some approach different than dingledooper

# Python 2, 27 bytes

```
lambda f,g,a,b:g(f(a),f(b))

```

Try it online!

# Answer
> 1 votes
# Zsh `-P`, 16 bytes

```
eval g '`f '$@\`

```

Try it online!

Expects the functions to be predefined as `f` and `g`.

The `-P` option makes the `$@` array expand to wrap the word around every element, e.g. `x$@y` with `A B` makes `xAy xBy` instead of `xA By`. This allows it to generalise implicitly for more than 2 inputs.

---

For 1 byte less, you can have an uninteresting answer that only works with 2 inputs:

# Zsh, 15 bytes

```
g `f $1` `f $2`

```

Try it online!

# Answer
> 1 votes
# Knight, 22 bytes

```
O E++P" "+=f+P" "+P+fP

```

Try it online!

Since knight doesn't have the concept of functions, this program instead takes in the "functions" as strings from standard in and outputs to standard out. Specifically, in `f`, `g`, `x` and `y` on separate lines in input, and outputs `g(f(x),f(y))`. It does this by combining the inputs into a single string, then evaluating (adding appropriate white space).

# Answer
> 1 votes
# Go, 70 bytes

```
type i=int
func o(f func(i)i,g func(i,i)i,l,r i)i{return g(f(l),f(r))}

```

Attempt This Online!

`int` shows up enough here to be aliased into a single character and save 3 bytes.

### Go, generic, 66 bytes

```
func o[T any](f func(T)T,g func(T,T)T,l,r T)T{return g(f(l),f(r))}

```

Attempt This Online!

Usually, generic solutions in Go are longer than the non-generic version. In this case, it's 4 bytes shorter.

# Answer
> 1 votes
# Elixir, 22 bytes

-1 byte thanks to @Steffan.

```
& &2.(&1.(&3),&1.(&4))

```

Try it online!

# Answer
> 1 votes
# Uiua, 5 bytes

```
^2∩^1

```

Try it!

```
^2∩^1
  ∩^1  # call the unary function on both inputs
^2     # call the binary function

```

# Answer
> 1 votes
# Kamilalisp, 15 bytes

```
(λ(f g)g&[f f])

```

Attempt This Online!

# Answer
> 0 votes
# dc, 16 bytes

```
4Rdsfxsrlfxlr3Rx

```

Try it online!

Takes input as the four preceding items on the stack, and pushes the result onto the stack.

# Answer
> 0 votes
# J-uby, 3 bytes

J-uby has this as a built-in. `:**` takes a pair of lambdas and returns a lambda that takes two arguments. It can be invoked like `:**[f,g][x,y]`, where `f` and `g` are lambdas and `x` and `y` are arguments to the returned lambda.

```
:**

```

Attempt This Online!

# Answer
> 0 votes
# K (ngn/k), 7 bytes

```
{x y z}

```

Try it online!

Simple. Apply function `y` to all numbers in `z`, then apply function `x` to the result.

---
Tags: code-golf, integer, functional-programming
---


title: Implement a cleave function

text:
# Question
Title: Implement a cleave function
Think of cleave as the conceptual inverse of map. If map applies a function to each number in a list...

`map([1, 2, 3], x -> x * 5)` -\> `[5, 10, 15]`

then cleave applies each function in a list to a number.

`cleave(5, [x -> x * 2, x -> x - 1, x -> x * x])` -\> `[10, 4, 25]`

More formally, given:

* \\$n\\$, an integer, and
* \\$L\\$, a list of black box functions with type signature `integer -> integer` or equivalent

Apply each function in \\$L\\$ to \\$n\\$, collecting the results in a list the same length as \\$L\\$. (It can be the same list if you want.)

## Challenge

Implement the cleave function in your language of choice.

## Format

You must accept an integer and a list of black box functions and output a list of integers in any reasonable format. Argument order doesn't matter. The list of functions is flexible. You may accept:

* A list of black box functions (including a list of function pointers, etc.).
* A variable number of black box functions as parameters (varargs).
* A number indicating how many functions to accept.
* Etc.

## Rules

* Builtins are allowed, but please consider adding a less trivial answer so we can see how cleave might be implemented in your language.
* Explaining your answer(s) is encouraged!
* Standard loopholes are forbidden.
* This is , so the code with the fewest bytes (in each language) wins.

## Test cases

Note: for simplicity, instead of showing functions like `x -> 10 * x`, I will show them like `10x`. Imagine there is an \\$f(x) =\\$ in front of each of these.

```
  3, [] -> []
 42, [x] -> [42]
  0, [10x, x/2, abs(x), -x] -> [0, 0, 0, 0]
  8, [10x, x/2, abs(x), -x] -> [80, 4, 8, -8]
 -5, [abs(x), -x, x+10] -> [5, 5, 5]
  5, [abs(x), -x, x+10] -> [5, -5, 15]
 10, [x*x, x/10, x*x + 2x + 1, 13, x%3 - 3] -> [100, 1, 121, 13, -2]
950, [x*x, x/10, x*x + 2x + 1, 13, x%3 - 3] -> [902500, 95, 904401, 13, -1]

```

# Answer
> 9 votes
# Haskell, 11 bytes

`map.flip($)`

(If using Stack, this can be dropped to 7 bytes: `map.(&)`.)

# Answer
> 8 votes
# Python 3, 27 bytes

```
lambda L,n:[g(n)for g in L]

```

Try it online!

Anonymous function that takes the list of functions and a number as arguments.

# Answer
> 8 votes
# JavaScript, 20 bytes

```
a=>n=>a.map(f=>f(n))

```

Try it online! or run all test cases (courtesy of Arnauld)

# Answer
> 7 votes
# Java (OpenJDK 8), 22 bytes

```
L->x->L.map(a->a.f(x))

```

Try it online!

-4 bytes thanks to Olivier Grégoire

`L` is a stream of `Function<Integer, Integer>` and `x` is an `int`. `Function` here is not `java.util.function.Function` but rather is a custom interface `Function<T, U>` with a single method `U f(T t)`. This is just to save bytes over the normal `Function<T, U>` which requires the method name `apply`, which is apparently allowed.

# Answer
> 6 votes
# Julia 1.0, 9 bytes

```
a^b=a.|>b

```

Try it online!

# Julia 1.6+, 3 bytes

As pointed out by @MarcMush, Julia 1.6 has since allowed defining `.|>` as a function, giving this 3-byter:

```
.|>

```

TIO does not offer Julia 1.6, but here's an interactive example:

```
julia> f=.|>
Base.Broadcast.BroadcastFunction(|>)
julia> println(f(5, [x->x*2, x->x-1, x->x*x]))
[10, 4, 25]

```

# Answer
> 5 votes
# C# (Visual C# Interactive Compiler), 23 bytes

```
a=>b=>b.Select(x=>x(a))

```

C# was born for this

Try it online!

# Answer
> 5 votes
# , 38 bytes

```
function(i,m)sapply(m,do.call,list(i))

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Unicode), 0 bytes

APL doesn't normally use lists of functions, but there are ways to use such. Even if the syntax for their creation is awkward, their use is simple: Try it online!

For the specific case of a list of integer↦integer functions, it is convenient to represent \\$L\\$ as a train, though it, despite appearances, isn't a list of functions. The calling syntax is identical to the above: Try it online!

If we absolutely wanted something that took \\$L\\$ and \\$n\\$ and applied \\$L\\$ to \\$n\\$ using the above juxtaposition syntax, we write a full program which prompts first for \\$\\$ and then for \\$L\\$, applying \\$L\\$ to \\$n\\$ by juxtaposition of the input values:

# APL (Dyalog Unicode), 2 bytes

```
⎕⎕

```

Each stylised console prompts for a value from the console (STDIN).

Try it online!

Alternatively, we could define an "apply" operator that takes \\$L\\$ on the left and \\$n\\$ on the right:

# APL (Dyalog Unicode), 5 bytes

```
{⍺⍺⍵}

```

`⍺⍺` is the left operand and  is the right argument.

Try it online!

# Answer
> 4 votes
# BQN, 7 bytes

```
{}¨⟜<

```

Try it!

-2 bytes from dzaima.

Takes a list of monadic BQN functions, returns a list of the same length.

# Answer
> 4 votes
# Ruby 2.7, 19 bytes

```
->a,b{b.map{_1[a]}}

```

Try it online!

Doesnt work on TIO cause of Numbered arguments.

# Answer
> 4 votes
# Raku, 13 bytes

```
{@^f».($^n)}

```

Try it online!

# Answer
> 4 votes
# \>= 4.1, 21 bytes

```
\(l,i)Map(\(x)x(i),l)

```

Try it online!

An anonymous function taking a list of functions and an integer and returning a list of integers.

TIO version uses `function` instead of `\` since TIO hasn’t been upgraded to R 4.1 yet.

# Answer
> 4 votes
# J-uby, 3 Bytes

```
:-@

```

J-uby actually has a built-in for this, despite me never having actually used it. You are intended to use it with `-[f, g, h]` to create a function that will "cleave" a provided argument over the functions in the array. `:-@` is the symbol for unary minus in Ruby, which is callable in J-uby. It would take input in the form `:-@.call(L).call(n)`.

But built-ins are boring. How would it be implemented otherwise?

# 13 Bytes

```
~:*%(:& &~:^)

```

There are basically three components to this function. First is `~:*` which just creates a flipped-argument map function: `->(a, f){ a.map(&f) }`.

Next, there is `:& &~:^`. This defines the "n-applicator" function: given the input `n`, this defines a function that will apply `n` to whatever function you pass it. Essentially, it’s equivalent to `->(n){ ->(f){ f[n] } }`. How does this work? `^` is the function application operator, so `~:^` is function application with flipped arguments: `->(x, f){ f[x] }`. Since `&` is the partial application operator, `:& & ~:^` means you partially apply the flipped function application operator to the partial application operator. Anyone else getting semantic satiation?

Finally, we've got `%` in the middle. The `%` operator has different functionalities depending on its arguments, but in this case it denotes a "hook": given a binary function `F` and a unary function `G`, it returns a function that applies `G` to one of its two arguments before passing them on to `F`: `F % G == ->(L,n){ F[L, G[n]] }`. In this case, that means calling a flipped map (`~:*`) on the input array L and the n-applicator function (`:& & ~:^`).

The result is mapping the n-applicator function over the supplied array of functions, applying n to each element of the array. In plain Ruby, it's equivalent to `->(L,n){ L.map { |f| f[n] } }`

# Answer
> 4 votes
# Elm, 14 bytes

```
(|>)>>List.map

```

`|>` is function application: `a |> f` means `f a`.

`>>` is function composition: `(f >> g) a` is `g (f a))`.

You can try it here. Here is a full test program:

```
import Html exposing (text)

f = (|>)>>List.map

main =
  f 5 [\x -> x * 2, \x -> x - 1, \x -> x * x]
  |> Debug.toString
  |> text

```

# Answer
> 3 votes
# Jelly, 2 bytes

```
v€

```

Try it online!

Accepts a list of functions on the left in Jelly source code and the value on the right.

```
v€  Main Link; (x: functions, y: value)
 €  For each function in x
v   Evaluate it at y

```

Less trivial answer:

# Jelly, 6 bytes

```
³Ç$Ð¡Ḋ

```

Try it online!

Full program that accepts the blackbox-functions as a tied function in the header (standard for inputting blackbox-functions for Jelly), the initial value in the third argument (first value), and the number of functions in the fourth argument (second value).

```
³Ç$Ð¡Ḋ    Main Link; (x: value, y: number of functions)
   Ð¡     Collecting intermediate values, repeat y times:
  $       - last two:
³           - x
 Ç          - call the helper link (the blackbox)
     Ḋ    All but the first element

```

Basically, calls the black-box N times, where each time the function cycles its behavior (that's how tie works), and collects all N+1 results, then removes the initial value.

# Answer
> 3 votes
# Vyxal, 1 byte

```
S

```

Try it Online!

A full program that takes `number` then `functions`.

## Explained

```
S # Converts each function to a string. This involves evaluating them, which somehow takes input from the stack.

```

Takes input in the header because that's how to input functions

# Answer
> 3 votes
# Standard ML (MLton), 19 bytes

(-1 from Laikoni by manipulating names and spacing on the original `fn n=>map(fn f=>f x)`.)

```
fn! =>map(fn f=>f!)

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 7 bytes

```
Through

```

Try it online!

Built-in. Input `[L[n]]`.

---

### Wolfram Language (Mathematica), 12 bytes

```
n#@n&/@#&

```

Try it online!

Input `[n][L]`.

# Answer
> 3 votes
# tinylisp, 37 bytes

```
(d C(q((F N)(i F(c((h F)N)(C(t F)N))(

```

Try it online!

### Ungolfed/explanation

```
(load library)     Library contains ungolfed aliases for builtins
(def cleave        Define cleave to be
 (lambda (F N)     a function taking a list of functions F and a number N
  (if F            If F is nonempty:
   (cons             Construct a list
    ((head F) N)      whose head is the first function in F applied to N
    (cleave           and whose tail is the result of a recursive call
     (tail F)         with the remaining functions in F
     N))              and the same number N
   nil))))         Else, return empty list

```

# Answer
> 3 votes
# Rust, 49 bytes

```
|u,k:Vec<Box<_>>|k.iter().map(|z|z(u)).collect();

```

Maximally abusing this ruling. Would be nearly twice as long if all types where specified.

Playground

# Answer
> 2 votes
# Factor \+ `combinators`, 6 bytes

```
cleave

```

Try it online!

Built-in.

# Answer
> 2 votes
# Jelly, 3 bytes

```
ṛĿⱮ

```

Try it online!

Takes \\$n\\$ on the left and a list of link indices on the right.

```
  Ɱ    For each element of the right argument,
ṛĿ     call the link at that index monadically on the left argument.

```

# Answer
> 2 votes
# Red, 32 bytes

```
func[g n][forall g[g/1: g/1 n]g]

```

Modifies the list in place. Doesn't work in `TIO`, but works fine in the Red GUI console:

Here's a `TIO`-compatible version:

# Red, 41 bytes

```
func[L n][collect[foreach g L[keep g n]]]

```

Try it online!

# Answer
> 2 votes
# Japt, 4 bytes

Takes the integer as input as a single digit array with the array of functions pre-assigned to variable `V`, outputs and array of single integer arrays.

```
V£mX

```

Try it

# Answer
> 2 votes
# C (gcc), ~~62~~ 52 bytes

```
f(n,L)int(**L)();{while(*L)printf("%d ",(*L++)(n));}

```

Try it online!

Takes `L` as a `NULL`-terminated array of pointers to functions taking an int and returning an int. Outputs results space-separated on stdout (with a trailing space).

-10 bytes from @EasyasPi

(also C++ (gcc), 79 bytes with `#include<cstdio>` and ANSI function syntax. Try it online! (C++))

---

If writing to a caller-allocated array that is passed to the function is a valid form of output, then:

# C (gcc), ~~59~~ 51 bytes

```
f(int n,int(**L)(),int*r){while(*L)*r++=(*L++)(n);}

```

Try it online!

Same input as above, but outputs results through `r`, which must point to at least as many `int`s as `L` does `int(*)(int)`s (not including `L`'s `NULL` terminator).

-8 bytes from @EasyasPi

(also C++ (gcc), 59 bytes \[Try it online! (C++)\]\[TIO-kq6vpd7q\])

# Answer
> 2 votes
# JavaScript, 43 bytes

I know there's already a nice JS entry, but I wanted to give it a go by giving both parameters to a single function. Different approach, same output.

Here's mine:

```
(n,a)=>a.reduce((A,F)=>A.concat([F(n)]),[])

```

Try it online! Also test cases (modified from Arnauld's imlementation).

This is NOT memory friendly because I had to create a new array each time I used `Array.prototype.concat`. It would have been much nicer and slightly shorter if JavaScript's `Array.prototype.push` would just return the modified array...

# Answer
> 2 votes
# Mlatu, 20 bytes

```
->n;{n swap call}map

```

Explanation: `->n;` pops off the stack and binds it to `n`. The list is left as the implicit parameter of `map` and is never bound. `{n swap call}` is a closure in Mlatu, which pushes `n` (the number) onto the stack, swaps the placement of the number and the function, and then calls the function with `n` as its argument. `map` takes the list and the closure and `map`s the list with the given closure.

# Answer
> 2 votes
# Binary Lambda Calculus, 58 bits = 8 bytes

```
0000010110000000000101110011111011111100101111011010000010

```

Try it online!

It's a higher-order function that takes in a Church numeral and a list and returns a list. The list encoding is the one where a list is identified with its right fold function (e.g. `[1, 2]` would be `\c n. c 1 (c 2 n)`). (I'm using `\` as \\$\lambda\\$ in this answer.)

**“Readable” version:**

```
\\@@1\\\\@@2@46@@321\\1

```

Here, I'm using prefix notation. `\` is abstraction and `@` is application. Numbers are de Bruijin indices (starting at 1). Of course, (for example) `321` here means `3`, then `2`, then `1`, not the number `321`.

**Actually readable version:**

```
\k l. l (\a b c n. c (a k) (b c n)) (\c n. n)

```

## Explanation

Todo. It’s late and I’m tired.

# Answer
> 2 votes
# Go, 78 bytes

```
func(x int,F[]func(int)int)(O[]int){for _,f:=range F{O=append(O,f(x))}
return}

```

Attempt This Online!

### Go, 79 bytes, generic

```
func f[T any](x T,F[]func(T)T)(O[]T){for _,f:=range F{O=append(O,f(x))}
return}

```

Attempt This Online!

# Answer
> 1 votes
# Lua, 55 bytes

```
function g(L,n)for k,v in pairs(L)do print(v(n))end end

```

Try it online!

# Answer
> 1 votes
# Proton, 19 bytes

```
L=>x=>[g(x)for g:L]

```

Try it online!

You might be wondering why I'm doing `fs.append` on each element. That's because making a list of functions errors when you try to print it or iterate through it - that's because it never becomes a list.

Observe this and notice that making a tuple of functions in Proton actually automatically cleaves.

# Answer
> 1 votes
# Perl 5, 27 bytes

```
sub{$x=shift;map&$_($x),@_}

```

Try it online!

# Answer
> 1 votes
# Scala, 14 bytes

```
x=>_.map(_(x))

```

Try it online!

# Answer
> 1 votes
# , 11 bytes

```
4 :'x`:0 y'

```

Try it online!

Called like:

```
+:`<:`*: f 5

```

In J, you cannot pass around a list "functions" (aka "verbs") directly, but you can pass around a list of "gerunds", which, like English gerunds, are noun-ified verbs.

Then you can use the "Evoke Gerund" conjunction, specifically the  ``:0` form of it, to call those gerunds as verbs again.

Doing this requires (afaik) an explicit verb, because conjunctions can only apply to a literal or a named variable. Here, the default LHS variable `x` represents the list of gerunds we are "evoking", and the integer we are applying them to is `y`.

## worth noting

This would be a very un-J thing to do, and if you wanted to solve this specific problem the natural solution would be to create a train like this:

```
+:,<:,*:

```

which creates a *single new verb*, rather than a list of verbs, but will produce the same output as the submission above when applied to `5`.

# Answer
> 1 votes
# Pip, 9 bytes

```
@Z{bM[a]}

```

A function that takes a number and a list of functions and returns a list of results. Try it online!

### Explanation

The `M`ap operator has a built-in ability to take a list of functions as its left argument. Unfortunately, it still expects the right argument to be a list of values, so we have to do some boxing and unboxing:

```
  {     }  Anonymous function
   bM        Map (each function in) the second argument
     [a]     to a list containing the first argument
           The result is a list of single-element lists
 Z         Zip: now we have a list containing a single list
@          Get the first (and only) element

```

# Answer
> 1 votes
# Squire (commit `a380c1f`), 53 bytes

```
journey f(n,a){i=N whilst(t=a[i=i+I])!=ni{a[i]=t(n)}}

```

Thou shalt call `f` like so:

```
# Example journeys
journey mul(n)
{
    reward n * II
}
journey sub(n)
{
    reward n - I
}
journey squ(n)
{
    reward n * n
}
# Createth a quest of journeys
quest = [ mul, sub, squ ]
# Number to cleave (thou might also use V directly)
n = V
# Embark on journey f
# f modifieth array in place.
f(n, array)
# Useth how thy wishes
# Array(Number(10), Number(4), Number(25))
dump(array)

```

#### Ungolfeth:

```
# Createth a journey named "cleave"
# It accepteth 2 arguments.
journey cleave(n, array)
{
    # Defineth a counter variable i with the mere value N.
    # Arrays are I-indexed; but we want to increment as we do things.
    counter = N
    # Alas, Squire doth not yet supporteth embarking directly
    # on journeys in arrays, so we musteth hire a mercenary.

    # Useth a property that going outside of an array's
    # kingdom will reward naught but ni ("null").
    whilst (mercenary = array[i = i + I]) != ni
    {
        # Embark the mercenary on his journey and
        # overwriteth array[i] with its reward.
        array[i] = mercenary(n)
    }
}

```

Note: I am trying to find a way to embed Squire on TIO, without much luck. It comes too close to the character limit to be useful.

# Answer
> 1 votes
# Groovy, 17 bytes

```
{n,L->L*.call(n)}

```

Try it online!

# Answer
> 1 votes
# Factor, 21 bytes

```
[ [ call ] with map ]

```

Try it online!

---

# Factor, 12 bytes

```
cleave>array

```

Try it online!

Builtin.

# Answer
> 1 votes
## Python2, 21 bytes

```
print[f(n)for f in l]

```

Makes use of Python 2's `print` being a keyword.

# Answer
> 1 votes
# Clojure, 17 bytes

```
#(for[f %&](f %))

```

Try it online!

Takes input as varargs where the first argument is the integer, and the rest are functions.

# Answer
> 1 votes
# 05AB1E, 3 bytes

```
€.V

```

Try it online or verify all test cases.

**Explanation:**

```
€    # Map over each function-string in the first (implicit) input-list:
 .V  #  Evaluate it as 05AB1E code, with the second (implicit) input-integer as argument
     # (and output the resulting list of values implicitly)

```

# Answer
> 1 votes
# tinylisp 2, ~~21~~ 18 bytes

```
(\(N)(p m(\(F)(F N

```

An anonymous function that takes its arguments curried: calling it on an integer returns a second function, and then calling that on a list of functions performs the cleaving.

You can try it at Replit. Example session:

```
tl2> (\(N)(p m(\(F)(F N
(() (N) (p m (\ (F) (F N))))
tl2> (def cleave _)
cleave
tl2> ((cleave 4) (list inc dec square))
(5 3 16)

```

### Explanation

The lexical scoping of tinylisp 2 makes this solution much simpler than my tinylisp solution.

```
(\(N)(p m(\(F)(F N))))
(\                   ) ; Lambda function
  (N)                  ; that takes an integer N:
     (p m           )  ;  Partially apply the map function to
         (\        )   ;  another lambda function
           (F)         ;  that takes a function F:
              (F N)    ;   Call F on N

```

The return value is a function that takes a list and maps the inner lambda over it. Calling this on a list of functions gives the desired result.

# Answer
> 1 votes
# Kamilalisp, 11 bytes

```
:^⍏&[#0 ⊙⍧]

```

Attempt This Online!

# Answer
> 0 votes
# Arturo, 20 bytes

```
$[n a][map a'f->f n]

```

Try it

# Answer
> 0 votes
# \>\<\> (Fish), 68 bytes

```
r1l2(?\$:' '=?/$:@2p1+10.
/$i   /
\
\$~{~r
>l ?\;/0.
\oan/ \e@':$'~\

```

Try it

(Assuming leading space is acceptable in input. See this for 76 bytes if not.)

Well this is challenging. My strategy for accepting a list of functions is to parse them from input separated by spaces, then write them to the source code along with some piping to preserve the input number. Then I push the input number to the stack and send the instruction pointer to the third row which is where the functions are written. Then I clean up some garbage values and output the result.

---
Tags: code-golf, functional-programming
---


title: Dot Product of Diagonals

text:
# Question
Title: Dot Product of Diagonals
This challenge is very simple. You are given as input a square matrix, represented in any sane way, and you have to output the dot product of the diagonals of the matrix.

The diagonals in specific are the diagonal running from top-left to bottom-right and from top-right to bottom-left.

# Test Cases

```
[[-1, 1], [-2, 1]]  ->  -3
[[824, -65], [-814, -741]]  ->  549614
[[-1, -8, 4], [4, 0, -5], [-3, 5, 2]]  ->  -10
[[0, -1, 0], [1, 0, 2], [1, 0, 1]]  ->  1

```

# Answer
# Jelly, ~~8~~ 6 bytes

```
×UŒDḢS

```

Try it online! or verify all test cases

### How it works

```
×UŒDḢS  Main link. Argument: M (matrix)

 U      Upend M, i.e., reverse each row.
,       Pair M and upended M.
  ŒD    Yield all diagonals.
    Ḣ   Head; extract the first, main diagonal.
     S  Reduce by sum.

```
> 5 votes

# Answer
# MATL, 8 bytes

```
t!P!*Xds

```

Input format is

```
[-1, -8, 4; 4, 0 -5; -3, 5, 2]

```

Try it online! Or verify all test cases.

### Explanation

```
t       % Take input matrix implicitly. Duplicate
!P!     % Flip matrix horizontally
*       % Element-wise product
Xd      % Extract main diagonal as a column vector
s       % Sum. Display implicitly

```
> 3 votes

# Answer
# APL (Dyalog), ~~15~~ 9 bytes

```
+/1 1⍉⌽×⊢

```

Try it online!

**How?**

`+/` \- sum

`1 1⍉` \- diagonal of

`⌽×⊢` \- element wise multiplication of the matrix with it's reverse
> 3 votes

# Answer
# J, ~~21~~ 19 bytes

```
[:+/(<0 1)|:(*|."1)

```

Straight-forward approach.

Saved 2 bytes thanks to @Lynn.

## Usage

The input array is shaped using `dimensions $ values`.

```
   f =: [:+/(<0 1)|:(*|."1)
   f (2 2 $ _1 1 _2 1)
_3
   f (2 2 $ 824 _65 _814 _741)
549614
   f (3 3 $ _1 _8 4 4 0 _5 _3 5 2)
_10
   f (3 3 $ 0 _1 0 1 0 2 1 0 1)
1

```

## Explanation

```
[:+/(<0 1)|:(*|."1)    Input: matrix M
              |."1     Reverse each row of M
             *         Multiply element-wise M and the row-reversed M
    (<0 1)|:           Take the diagonal of that matrix
[:+/                   Sum that diagonal and return it=

```
> 2 votes

# Answer
# Julia, 25 bytes

```
~=diag
!x=~x⋅~rotl90(x)

```

Try it online!
> 2 votes

# Answer
# Python, 47 bytes

```
lambda x:sum(r[i]*r[~i]for i,r in enumerate(x))

```

Test it on Ideone.
> 2 votes

# Answer
## JavaScript (ES6), 45 bytes

```
a=>a.reduce((r,b,i)=>r+b[i]*b.slice(~i)[0],0)
a=>a.reduce((r,b,i)=>r+b[i]*b[b.length+~i],0)

```
> 1 votes

# Answer
## R, 26 bytes

```
sum(diag(A*A[,ncol(A):1]))

```
> 1 votes

# Answer
# Mathematica, 17 bytes

```
Tr[#~Reverse~2#]&

```
> 1 votes

# Answer
## Clojure, 57 bytes

```
#(apply +(map(fn[i r](*(r i)(nth(reverse r)i)))(range)%))

```
> 0 votes

# Answer
# Haskell, ~~80~~ 48 bytes

I liked my previous solution more, but this is much shorter (basically does the same as the Python solution):

```
f m=sum[r!!i*r!!(length m-i-1)|(i,r)<-zip[0..]m]

```

Try it online!
> 0 votes

# Answer
# J, 18 Bytes

```
<:@#{+//.@:(*|."1)

```

### Explaination:

```
           (     ) | Monadic hook
            *      | Argument times...
             |."1  | The argument mirrored around the y axis
     +//.@:        | Make a list by summing each of the diagonals of the matrix
    {              | Takes element number...
<:@#               | Calculates the correct index (size of the array - 1)

```
> 0 votes

# Answer
# 05AB1E, 5 bytes

```
í*Å\O

```

Try it online or verify all test cases.

**Explanation:**

```
í        # Reverse each row of the (implicit) input-matrix
         #  i.e. [[-1,-8,4],[4,0,-5],[-3,5,2]] → [[4,-8,-1],[-5,0,4],[2,5,-3]]
 *       # Multiply it with the (implicit) input-matrix (at the same positions)
         #  i.e. [[-1,-8,4],[4,0,-5],[-3,5,2]] and [[4,-8,-1],[-5,0,4],[2,5,-3]]
         #   → [[-4,64,-4],[-20,0,-20],[-6,25,-6]]
  Å\     # Get the diagonal-list from the top-left corner towards the bottom-right
         #  i.e. [[-4,64,-4],[-20,0,-20],[-6,25,-6]] → [-4,0,-6]
    O    # Sum it (and output implicitly)
         #  i.e. [-4,0,-6] → -10

```
> 0 votes

# Answer
# Kamilalisp, 46 bytes

```
$(⌿⊙← +)∘∊∘[* #0 [$(⌼ =) #0 #0]∘⍳∘⍴]∘[* #0 :⌽]

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, math, matrix, linear-algebra
---