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 code-golf, 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]
46 Answers 46
Haskell, 11 bytes
map.flip($)
(If using Stack, this can be dropped to 7 bytes: map.(&)
.)
-
1\$\begingroup\$ Really is a shame
&
isn't there by default \$\endgroup\$Unrelated String– Unrelated String2021年06月21日 06:49:35 +00:00Commented Jun 21, 2021 at 6:49 -
2\$\begingroup\$
x#y=x<*>[y]
also works for same bytecount I think? \$\endgroup\$Bubbler– Bubbler2021年06月21日 07:11:01 +00:00Commented Jun 21, 2021 at 7:11 -
1\$\begingroup\$ @Bubbler As does
f x=map($x)
\$\endgroup\$Unrelated String– Unrelated String2021年06月21日 07:15:28 +00:00Commented Jun 21, 2021 at 7:15 -
\$\begingroup\$ And
\x->map($x)
. \$\endgroup\$NoLongerBreathedIn– NoLongerBreathedIn2021年06月21日 14:30:58 +00:00Commented Jun 21, 2021 at 14:30
Python 3, 27 bytes
lambda L,n:[g(n)for g in L]
Anonymous function that takes the list of functions and a number as arguments.
JavaScript, 20 bytes
a=>n=>a.map(f=>f(n))
Try it online! or run all test cases (courtesy of Arnauld)
-
1\$\begingroup\$ All test cases \$\endgroup\$Arnauld– Arnauld2021年06月21日 06:50:45 +00:00Commented Jun 21, 2021 at 6:50
-
\$\begingroup\$ @Arnauld, i think you accidentally switched the array and the number in the test cases \$\endgroup\$user100752– user1007522021年06月21日 06:57:01 +00:00Commented Jun 21, 2021 at 6:57
-
\$\begingroup\$ @EliteDaMyth Ah, yes. I was taking the parameters the other way around in my version and just pasted Shaggy's code without noticing. \$\endgroup\$Arnauld– Arnauld2021年06月21日 06:59:52 +00:00Commented Jun 21, 2021 at 6:59
-
1\$\begingroup\$ Thanks, @Arnauld :) No way was I fiddling about on my phone to reformat all those! \$\endgroup\$Shaggy– Shaggy2021年06月21日 10:59:22 +00:00Commented Jun 21, 2021 at 10:59
Java (OpenJDK 8), 22 bytes
L->x->L.map(a->a.f(x))
-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.
-
\$\begingroup\$ very nice. It was out of my expectation that java supports functions \$\endgroup\$wasif– wasif2021年06月21日 07:35:21 +00:00Commented Jun 21, 2021 at 7:35
-
\$\begingroup\$ Mmm reminds me of my own java \$\endgroup\$2021年06月21日 11:19:08 +00:00Commented Jun 21, 2021 at 11:19
-
2\$\begingroup\$ You can define your own interface
interface F { int f(int x); }
instead ofFunction<Integer, Integer>
. Works the same, and you spare 5 bytes like this:L->x->L.map(a->a.f(x))
\$\endgroup\$Olivier Grégoire– Olivier Grégoire2021年06月21日 15:03:38 +00:00Commented Jun 21, 2021 at 15:03 -
\$\begingroup\$ @OlivierGrégoire oh, that's allowed? well, that's very clever - thanks \$\endgroup\$2021年06月21日 15:05:49 +00:00Commented Jun 21, 2021 at 15:05
-
2\$\begingroup\$ @hyper-neutrino That's one of the tools that we (Java golfers) use all the time. so yes, it's definitely allowed. Technically, in regards of golfing, what's the difference between an imported
Function<F,T>
interface and a customly definedF
interface? Absolutely zero difference. \$\endgroup\$Olivier Grégoire– Olivier Grégoire2021年06月21日 15:09:10 +00:00Commented Jun 21, 2021 at 15:09
Julia 1.0, 9 bytes
a^b=a.|>b
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]
-
\$\begingroup\$ in Julia 1.6
f=.|>
works, getting the answer down to 3 bytes \$\endgroup\$MarcMush– MarcMush2021年06月21日 07:50:12 +00:00Commented Jun 21, 2021 at 7:50 -
\$\begingroup\$ @MarcMush Thanks, I did not know about this feature! \$\endgroup\$dingledooper– dingledooper2021年06月23日 04:08:58 +00:00Commented Jun 23, 2021 at 4:08
Ruby 2.7, 19 bytes
->a,b{b.map{_1[a]}}
Doesnt work on TIO cause of Numbered arguments.
-
2\$\begingroup\$ wow, ninja'd by 11 seconds \$\endgroup\$Razetime– Razetime2021年06月21日 07:11:55 +00:00Commented Jun 21, 2021 at 7:11
-
\$\begingroup\$ @Razetime phew. \$\endgroup\$user100752– user1007522021年06月21日 07:13:27 +00:00Commented Jun 21, 2021 at 7:13
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).
Alternatively, we could define an "apply" operator that takes \$L\$ on the left and \$n\$ on the right:
APL (Dyalog Unicode), 5 bytes
{⍺⍺⍵}
-
3\$\begingroup\$ I downvoted this answer because firstly I don't think it's fair to say there is a 0 byte solution here, as there isn't. It doesn't define a full program or function which performs the task. Also, I don't think using a train here is really in keeping with the actual question. The fact it happens to 'look' like a list in other languages is merely coincidence, might fool non APLers, but doesn't fool me! \$\endgroup\$rak1507– rak15072021年06月21日 07:04:43 +00:00Commented Jun 21, 2021 at 7:04
-
1\$\begingroup\$ @rak1507 I think the
L←N.f
part is valid, though the L0-5 variables aren't \$\endgroup\$Jo King– Jo King2021年06月21日 07:15:09 +00:00Commented Jun 21, 2021 at 7:15 -
3\$\begingroup\$ @rak1507 I discussed it with OP in the sandbox, and they wanted see this 0-byte approach, so I included it here, but also made sure to have actual program/function solutions included. Correct, trains are not lists of functions, which is why I included a link to their explanation. I wasn't trying to fool anyone. Anyway, I've now made it explicit that they are not lists of functions, and the "real" solution is the via-namespaces one, which is actually a real list of functions. I included trains because it was interesting and they had identical usage to the proper list approach. \$\endgroup\$Adám– Adám2021年06月21日 07:39:40 +00:00Commented Jun 21, 2021 at 7:39
-
1\$\begingroup\$ I'm still not convinced that it is valid, ⎕NC 'L' is 3, so it's a function not a list of functions. \$\endgroup\$rak1507– rak15072021年06月21日 07:45:57 +00:00Commented Jun 21, 2021 at 7:45
-
1\$\begingroup\$ @rak1507 It really is a list of function (I have inside info about how the interpreter works), but since functions cannot take functions as arguments,
≢
and⊃
don't work on them. \$\endgroup\$Adám– Adám2021年06月21日 08:03:14 +00:00Commented Jun 21, 2021 at 8:03
-
\$\begingroup\$ This language is insanity. It's like a code golfer wrote the sequel to Perl but wanted to include all of the other languages as well, and the result is beautiful. \$\endgroup\$Silvio Mayolo– Silvio Mayolo2021年08月12日 14:38:40 +00:00Commented Aug 12, 2021 at 14:38
R >= 4.1, 21 bytes
\(l,i)Map(\(x)x(i),l)
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.
BQN, 7 bytes
{Wx} ̈⟜<
-2 bytes from dzaima.
Takes a list of monadic BQN functions, returns a list of the same length.
-
\$\begingroup\$ Take \$L\$ as a train for 0 bytes :-) \$\endgroup\$Adám– Adám2021年06月21日 07:02:30 +00:00Commented Jun 21, 2021 at 7:02
-
\$\begingroup\$ Your
≍
function isn't an integer↦integer function. \$\endgroup\$Adám– Adám2021年06月21日 07:03:49 +00:00Commented Jun 21, 2021 at 7:03 -
\$\begingroup\$ i don't think there's a way to have a 0-byte function. \$\endgroup\$Razetime– Razetime2021年06月21日 07:07:27 +00:00Commented Jun 21, 2021 at 7:07
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 :[email protected](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] } }
-
\$\begingroup\$ I've been looking at a lot of j-uby answers lately. Is there any sort of tutorial other than the docs in the README? \$\endgroup\$Razetime– Razetime2021年07月23日 08:27:03 +00:00Commented Jul 23, 2021 at 8:27
-
\$\begingroup\$ @Razetime The Readme is it. I might make a better tutorial some time if people are interested \$\endgroup\$Cyoce– Cyoce2021年07月23日 17:54:13 +00:00Commented Jul 23, 2021 at 17:54
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
Vyxal, 1 byte
S
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
Jelly, 2 bytes
v€
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
3Ç$СḊ
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).
3Ç$СḊ Main Link; (x: value, y: number of functions)
С Collecting intermediate values, repeat y times:
$ - last two:
3 - 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.
Wolfram Language (Mathematica), 7 bytes
Through
Built-in. Input [L[n]]
.
Wolfram Language (Mathematica), 12 bytes
n#@n&/@#&
Input [n][L]
.
Binary Lambda Calculus, 58 bits = 8 bytes
0000010110000000000101110011111011111100101111011010000010
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.
-
\$\begingroup\$ This can be shortened to the 54 bit \k\l. l (\a\b\c\n. c (a k) (b c n)) l. \$\endgroup\$John Tromp– John Tromp2024年10月21日 21:00:21 +00:00Commented Oct 21, 2024 at 21:00
tinylisp, 37 bytes
(d C(q((F N)(i F(c((h F)N)(C(t F)N))(
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
-
\$\begingroup\$ shouldn't
(load library)
be a part of the bytes counted? \$\endgroup\$Razetime– Razetime2022年01月25日 06:05:57 +00:00Commented Jan 25, 2022 at 6:05 -
\$\begingroup\$ The actual solution doesn't use the library, just the test cases do. \$\endgroup\$DLosc– DLosc2022年01月25日 06:15:01 +00:00Commented Jan 25, 2022 at 6:15
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!)
-
1\$\begingroup\$ 19 bytes:
fn$ =>map(fn f=>f$)
\$\endgroup\$Laikoni– Laikoni2022年02月21日 16:07:32 +00:00Commented Feb 21, 2022 at 16:07
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.
-
1\$\begingroup\$ Hm. I asked for a list and you gave me a stack full of numbers. \$\endgroup\$chunes– chunes2021年06月21日 07:13:26 +00:00Commented Jun 21, 2021 at 7:13
Jelly, 3 bytes
ṛL·Ɱ
Takes \$n\$ on the left and a list of link indices on the right.
Ɱ For each element of the right argument,
ṛL· call the link at that index monadically on the left argument.
C (gcc), (削除) 62 (削除ここまで) 52 bytes
f(n,L)int(**L)();{while(*L)printf("%d ",(*L++)(n));}
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);}
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])
-
1\$\begingroup\$ You can save a lot of you drop C++ support, as C lets you do implicit int, K&R definitions, and empty parameter lists \$\endgroup\$EasyasPi– EasyasPi2021年06月22日 00:09:49 +00:00Commented Jun 22, 2021 at 0:09
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...
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.
-
\$\begingroup\$ Welcome to Code Golf! Nice first answer. \$\endgroup\$2021年06月24日 03:33:55 +00:00Commented Jun 24, 2021 at 3:33
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)
m
\$\endgroup\$