title: Depalindromize this string!

text:
# Question
Title: Depalindromize this string!
Given a palindrome generated according to this challenge, depalindromize it.

### Test cases

```
abcdedcba -> abcde
johncenanecnhoj -> johncena
ppapapp -> ppap
codegolflogedoc -> codegolf

```

As this is about depalindromizing, **your code cannot be a palindrome**.

Remember, this is , so the code with the fewest bytes wins.

# Answer
# Julia, ~~21~~ 15 bytes

```
x->x[1:end/2+1]

```

Try it online! (extra code is for printing output)
> 14 votes

# Answer
# 05AB1E, 3 bytes

```
2ä¬

```

Uses the **CP-1252** encoding. Try it online!
> 12 votes

# Answer
# Python 2, 23 bytes

I am not able to test on my phone, but this should work:

```
lambda s:s[:-~len(s)/2]

```
> 6 votes

# Answer
# Fuzzy Octo Guacamole, 4 bytes

```
2.^/

```

I spent a while searching for a language in which this challenge is short, and realized I was dumb and my own language did that.
> 6 votes

# Answer
# 05AB1E, 5 bytes

```
Dg;î£

```

Try it online!

**Explanation:**

```
D      Duplicate
 g;î   Divide length by two and round up
    £  First b letters of a

```
> 5 votes

# Answer
# Cheddar, ~~22~~ 18 bytes

```
@.head($0.len/2+1)

```

So simple I don't think needs explanation but I'll add one if wanted.

Try it online
> 5 votes

# Answer
# Pyth - 4 bytes

```
hc2Q

```

Test Suite.
> 4 votes

# Answer
# JavaScript (ES6), ~~32 26~~ 25 bytes

1 byte saved thanks to Neil:

```
s=>s.slice(0,-s.length/2)

```

```
f=
  s=>s.slice(0,-s.length/2)
;
console.log(f('abcdedcba'))
console.log(f('johncenanecnhoj'))
console.log(f('ppapapp'))
console.log(f('codegolflogedoc'))
```

---

**Previous solutions**
26 bytes thanks to Downgoat:

```
s=>s.slice(0,s.length/2+1)

```

32 bytes:

```
s=>s.slice(0,(l=s.length/2)+l%2)

```
> 4 votes

# Answer
# WinDbg, ~~87~~ 71 bytes

```
db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};da$t0 L(@$t1-@$t0)/2

```

*-16 bytes by not inserting NULL, instead passing length to `da`*

Input is passed in via an address in psuedo-register `$t0`. For example:

```
eza 2000000 "abcdedcba"       * Write string "abcdedcba" into memory at 0x02000000
r $t0 = 33554432              * Set $t0 = 0x02000000
* Edit: Something got messed up in my WinDB session, of course r $t0 = 2000000 should work
* not that crazy 33554432.

```

It works by replacing the right of middle char (or right-middle if the string has even length) with a null and then prints the string from the original starting memory address.

```
db $t0 L1;                                   * Set $p = memory-at($t0)
.for (r $t1 = @$t0; @$p; r $t1 = @$t1 + 1)   * Set $t1 = $t0 and increment until $p == 0
{
    db $t1 L1                                * Set $p = memory-at($t1)
};
da $t0 L(@$t1-@$t0)/2                        * Print half the string

```

Output:

```
0:000> eza 2000000 "abcdeedcba"
0:000> r $t0 = 33554432
0:000> db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};da$t0 L(@$t1-@$t0)/2
02000000  61                                               a
02000000  61                                               a
02000001  62                                               b
02000002  63                                               c
02000003  64                                               d
02000004  65                                               e
02000005  65                                               e
02000006  64                                               d
02000007  63                                               c
02000008  62                                               b
02000009  61                                               a
0200000a  00                                               .
02000000  "abcde"

```
> 4 votes

# Answer
## Haskell, 27 bytes

```
take=<<succ.(`div`2).length

```

Pointfree version of

```
\x->take(div(length x)2+1)x

```

which is also 27 bytes.
> 3 votes

# Answer
# MATL, ~~7~~ 6 bytes

```
9LQ2/)

```

Try it online!

### Explanation

```
9L       % Push array [1, 1j]
  Q      % Add 1: transforms into [2, 1+1j]
   2/    % Divide by 2: transforms into [1, 0.5+0.5j]
     )   % Apply as index into implicit input. The array [1, 0.5+0.5j] used as an index
         % is interpreted as [1:0.5+end*0.5]

```
> 3 votes

# Answer
# Jelly, 4 bytes

```
œs2Ḣ

```

Try it online!

### Explanation

```
œs2      Split input into 2 chunks of similar lengths. For odd-length input,
         the first chunk is the longest
   Ḣ     Keep the first chunk

```
> 3 votes

# Answer
# , 12 bytes

Two *completely* different solutions, both 12 bytes.

```
ò"Bx$xh|ò"bP

```

Try it online!

```
Ó./&ò
MjdGÍî

```

Try it online!
> 3 votes

# Answer
# Brachylog, 4 bytes

```
@2tr

```

Try it online!

### Explanation

```
@2        Split in half
  t       Take the second half
   r      Reverse it

```

If the input has odd length, the second half generated by `@2` is the one that is the longest, that is the one we should return (after reversing it).
> 3 votes

# Answer
# Java 7, 57 bytes

```
String c(String s){return s.substring(0,s.length()/2+1);}

```
> 3 votes

# Answer
# Dyalog APL, 9 bytes

```
⊢↑⍨2÷⍨1+≢

```

the argument

`↑⍨` truncated at

`2÷⍨` half of

`1+` one plus

the length

TryAPL online!
> 3 votes

# Answer
# Perl, 15 bytes

Includes +2 for `-lp`

Give input string on STDIN:

```
depal.pl <<< "HelleH"

```

`depal.pl`:

```
#!/usr/bin/perl -lp
s/../chop/reg

```

The `-l` is not really needed if you input the palindrome without final newline, but I included it to be fair to the other perl solutions that use it.
> 3 votes

# Answer
# PHP, 40 bytes

```
<?=substr($a=$argv[1],0,1+strlen($a)/2);

```

`strlen($a)/2` gets cast to int, with the input always having odd length, `+1` suffices to round up.

**42 bytes** for any length:

```
<?=substr($a=$argv[1],0,(1+strlen($a))/2);

```

for unknown length, `(1+strlen)/2` gets cast to int, rounding up `strlen/2`.
> 2 votes

# Answer
# TI-Basic, 14 bytes

Standard function. Returns string from index 1 to index (length/2 + 1/2).

```
sub(Ans,1,.5+.5length(Ans

```
> 2 votes

# Answer
# GameMaker Language, 59 bytes

```
a=argument0 return string_copy(a,1,ceil(string_length(a)/2)

```
> 2 votes

# Answer
# C, ~~31~~ 30 bytes

Saving 1 byte thanks to Cyoce.

```
f(char*c){c[-~strlen(c)/2]=0;}

```

Usage:

```
main(){
 char a[]="hellolleh";
 f(a);
 printf("%s\n",a);
}

```
> 2 votes

# Answer
# Actually, 5 bytes

```
l½KßH

```

Try it online!

*-1 byte thanks to Sherlock9*

Explanation:

```
l½K@H
l½K    ceil(len(input)/2)
   ßH  first (len(input)//2 + 1) characters of input

```
> 2 votes

# Answer
# Perl, 23 + 2 (`-pl` flag) = ~~28~~ 25 bytes

```
perl -ple '$_=substr$_,0,1+y///c/2'

```

Ungolfed:

```
while (<>) {             # -p flag
    chomp($_)            # -l flag
    $_ = substr($_, 0, 1 + length($_) / 2);
    print($_, "\n")      # -pl flag
}

```

Thanx to @ardnew.
> 2 votes

# Answer
# Dip, 8 bytes

```
H{C'0ÏEI

```

Explanation:

```
           # Implicit input
 H         # Push length of input
  {        # Add 1
   C       # Divide by 2
    '      # Convert to int
     0Ï    # Get string back
       E   # Push prefixes of string
        I  # Push prefixes[a]
           # Implicit print

```

This could probably be much improved.
> 2 votes

# Answer
# Pyth, ~~8~~ 7 bytes

```
<zh/lz2

```

Saved 1 with thanks to @Steven H

Not the shortest Pyth answer (by half) but I'm making an effort to learn the language and this is my first post using it. Posted as much for comments and feedback as anything. It's also the first Pyth program that I have actually got to work :)

Now I just need to work out how the 4 byte answer from @Maltysen works :-)
> 2 votes

# Answer
# Perl, 14 + 3 (`-lF` flag) = ~~19~~ 17 bytes

For 5.20.0+:

```
perl -lF -E 'say@F[0..@F/2]'

```

For 5.10.0+ (19 bytes):

```
perl -nlaF -E 'say@F[0..@F/2]'

```

Ungolfed:

```
while (<>) {             # -n flag (implicitly sets by -F in 5.20.0+)
    chomp($_)            # -l flag
    @F = split('', $_);  # -aF flag (implicitly sets by -F in 5.20.0+)
    say(@F[0 .. (scalar(@F) / 2)]);
}

```

Thanx to @simbabque.
> 2 votes

# Answer
# Befunge, ~~24~~ 22 bytes

```
~:0`!#v_\1+
0:-2,\_@#`

```

Try it online!

---

Befunge has no string or array type so the everything is done on the stack one character at a time. The first loop (on the top line) counts the number of characters read (swapping with less than 2 elements in the stack produces an initial 0). The second (on the middle line) prints characters while counting down twice as fast. As a result only the last half of the input is printed, but LIFO so it's in the correct order.

Thanks to Brian Gradin for a better version of the first loop.
> 2 votes

# Answer
## Brainfuck, 20 bytes

```
,
[
  [>,]
  <[<]
  >.,>[>]
  <<
]

```

Try it online.

This saves a byte over the more straightforward approach of consuming the input before starting the main loop:

```
,[>,]
<
[
  [<]
  >.,>[>]
  <,<
]

```
> 2 votes

# Answer
# Python 2, 23 bytes

```
lambda x:x[:len(x)/2+1]

```
> 1 votes

# Answer
# MATLAB / Octave, ~~20~~ ~~19~~ ~~18~~ 16 bytes

*1 byte off borrowing an idea from Easterly Irk's answer (add `1` instead of `.5`)*
*2 bytes off thanks to @StewieGriffin (unnecessary parentheses)*

```
@(x)x(1:end/2+1)

```

Try it at Ideone.
> 1 votes

# Answer
# C# ~~51~~ 50 bytes

```
s=>string.Join("",s.Where((_,i)=>i<=s.Count()/2));

```

It's a lambda, woo!
You can catch it with:

```
Func<string,string> f=<your lambda here>

```

it requires the string to be a palindrome.
> 1 votes

# Answer
## Pyke, 4 bytes

```
le>_

```

Try it here!

```
l    -    len(input)
 e   -   ^//2
  >  -  input[^:]
   _ - reversed(^)

```
> 1 votes

# Answer
# IBM/Lotus Notes Formula, 21 bytes

```
@Left(a;@Length(a)/2)

```

Computed field that takes input from an editable field a. Works because Notes rounds up when an odd number is divided by 2.

Test Cases
> 1 votes

# Answer
# Retina, 24 bytes

I basically took this from another answer of mine.

```
^((.)*?.??)(?<-2>.)*$
$1

```

**Try it online**
> 1 votes

# Answer
## Racket 48 bytes

```
(substring s 0(+ 1(floor(/(string-length s)2))))

```

Ungolfed:

```
(define (f s)
  (substring s 0 (+ 1
                    (floor
                     (/ (string-length s)
                        2)))))

```

Testing:

```
(f "abcdedcba")
(f "johncenanecnhoj")
(f "ppapapp")
(f "codegolflogedoc")

```

Output:

```
"abcde"
"johncena"
"ppap"
"codegolf"

```
> 1 votes

# Answer
# CJam, 7 bytes

```
r_,-2/<

```

Try it online!
> 1 votes

# Answer
# GO, 43 bytes

`func(s string)string{return s[:len(s)/2+1]}`

Try it online!
> 1 votes

# Answer
# Python 2, 22 bytes

```
lambda _:_[len(_)/2:]

```

Depalindromizes a given string. Still fails on all the test cases. Weird... ;-)
> 1 votes

# Answer
# Python 3.5, 87 Bytes

```
x=list(input())
for q in range(0,int(round((len(x)/2)-0.1,0))):x.pop()
print(''.join(x))

```

i'm new to this codegolfing, but it's to be fun. I probably won't win but oh well.
> 1 votes

# Answer
# Hexagony, 56 bytes

This is awful, but I just wanted to do it in Hexagony :)

Golfed:

```
,<_..){/"./..\&..$@....>;{.....'..>"+"+"&"='&'&=}\}=.:(<

```

In a hexagon:

```
     , < _ . .
    ) { / " . /
   . . \ & . . $
  @ . . . . > ; {
 . . . . . ' . . >
  " + " + " & " =
   ' & ' & = } \
    } = . : ( <
     . . . . .

```

Way to many no-ops...
> 1 votes

# Answer
## \>\<\>, ~~7~~ 15 bytes

```
l1+2,[v
 ;!?lo<

```

Try it here!

This is a full program. To use it simply place the palindrome on the stack, and the result will be outputted to stdout!

**Explanation**

```
l       get the stack length
 1+     add one
   2,   divide by two
     [  pop the value, create a new stack of that length

```

That's the meat of it, `ol?!;` just outputs until the stack is empty.

## \*\>\<\>, 11 bytes (non-competing)

```
l5+2,]r{[$.

```

Try it here! (first line is a program that calls the function, outputs the stack, then exits)

This is a function. To use it simply call it (instruction `C`) with the palindrome on the stack, and the result will be on the stack! This part is non-competing because \*\>\<\> is younger than the challenge.

**Explanation**

```
l             get the stack length
 5+           add five
   2,         divide by two
     ]        close the stack
      r       reverse the stack
       {      shift the stack left
        [     pop the value on the end, create a new stack of that length
         $    swap the two values on the end of the stack
          .   jump back, with the result on the stack

```

For \>\<\> coders who might be confused by this, a new stack is created when a function is called, so you can actually call `]` right from the start if you're inside a function. The data inside this stack is the `x, y` coordinate of the \>\<\> when `C` was called.
> 1 votes

# Answer
## Keg, 7 bytes

```
^(!2/|_

```

That is easy but really hard to golf.

## Explanation

```
^       # Input in the right order
 (!2/   # Repeat half of length times:
     |_ # Pop the stack

```

TIO
> 1 votes

# Answer
# , 35 bytes

```
substr(x<-scan(,''),1,nchar(x)/2+1)

```

Try it online!
> 1 votes

# Answer
# Vyxal, 2 bytes

```
½h

```

Try it Online!

Makes a list of each half of the string and takes the first item. Vyxal rounds up when splitting odd numbers in half. Don't think this can be golfed to 1 byte because the code can't be a palindrome :p
> 1 votes

# Answer
## Ruby, ~~21~~ 19 bytes

```
->s{s[0..s.size/2]}

```
> 0 votes

# Answer
## Haskell, 27 bytes

```
f[x]=[x]
f(a:b)=a:f(init b)

```

No indexing. Recursively takes from the start and end, keeping letters from the end.
> 0 votes

# Answer
# Perl 6, 21 bytes

```
*.substr(0,1+* div 2)

```

## Expanded:

```
*\            # Whatever lambda
.substr(
  0,
  1 + * div 2 # Whatever lambda
)

```
> 0 votes

# Answer
# Dyalog APL, 9 bytes

```
⊢↑⍨2÷⍨1+⍴

```

Thanks to Adám for saving 4 bytes.
> 0 votes

# Answer
# Brain-Flak, 45 bytes

```
([][()]<>){({}[()()])<>{}<>}<>{({}<>)<>}<>

```

Try it online!

42 bytes of code, and `+3` for the -c flag which enables ASCII input and output.
> 0 votes

# Answer
# Python 3, ~~28~~ ~~26~~ 24 bytes

Python 3 strings don't like non-int indexes...

```
lambda S:S[:len(S)//2+1]

```

Alternatively, with the same byte count,

```
lambda S:S[:-~len(S)//2]

```
> 0 votes

# Answer
# Java 7, 57 bytes

```
String c(String s){return s.substring(0,-~s.length()/2);}

```

At first I misinterpreted the question and also made code that supported even palindromes (which isn't necessary due to this being the reverse of that other challenge, and therefore there aren't any even palindrome test-cases). So I deleted my answer.
After seeing *@KarlNapf*'s great answer however, I undeleted and edited this. It's the same byte count as the other Java 7 answer, but works for both odd and even length palindromes (although only odd were asked for this challenge).

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(String s){
    return s.substring(0, -~s.length()/2);
  }

  public static void main(String[] a){
    System.out.println(c("abcdedcba"));
    System.out.println(c("abcddcba"));
  }
}

```

**Output:**

```
abcde
abcd

```
> 0 votes

# Answer
# Python 3, 26 bytes

```
lambda c:c[:(len(c)+1)//2]

```

This squeezes 2 chars out of the other Python3 answer by replacing the `int()` with division with `//`.
> 0 votes

# Answer
# R, 59 bytes

Not pretty but it gets the job done.

```
cat(strsplit(scan(,""),"")[[1]][0:(nchar(x)%/%2)+1],sep="")

```
> 0 votes

# Answer
## GolfSharp, 20 bytes

```
v=>v.R(0,v.L()/2+1);

```
> 0 votes

# Answer
# PowerShell, ~~46~~ 36 bytes

Unfortunately there's no PowerShell on Try it Online. Alas, here's my attempt.

`$args[0][0..(($args[0].Length-1)/2)]`
> 0 votes

# Answer
# QBIC, 18 bytes

```
;?left$$|(A,_lA|/2)

```

`;` gets a command line parameter, then we print the left half of it using `_l`. Works fine for even and odd-length strings.
> 0 votes

# Answer
# Lua, 28 bytes

```
x=...print(x:sub(1,#x//2+1))

```
> 0 votes

# Answer
## Common Lisp, 43

```
(lambda(s)(subseq s 0(ceiling(length s)2)))

```

Truly hard to golf without accidentally writing a palindrome, will all those `(` matching opposite `)`.

I know, this is not what "palindrome" means.
> 0 votes

# Answer
# Element, 11 bytes

```
_2:$'[(`)#]

```

Try it online!

```
_2:$'[(`)#]
_             take input
 2:           make a second copy
   $          length of string
    '[    ]   FOR loop
     [(`  ]   chop off then print the first character
     [  )#]   chop off then discard the last character

```

The FOR loop is actually executed about twice as many times as it needs to be, but those extra iterations do not affect the output since it runs out of data to print.
> 0 votes

# Answer
# Scala, 21 bytes

```
a=>a.take(a.size/2+1)

```

requires an assignment with a type annotation: `val f:(Seq[_]=>Seq[_])...`
> 0 votes

# Answer
## Clojure, 30 bytes

Clojure port of basically every answer here:

```
#(subs % 0(inc(/(count %)2)))

```

Should be self explanatory.
> 0 votes

# Answer
# Java 8, 33 bytes

Same logic as @Numberknot, but with 24 less bytes due to the use of lambdas. I tried to add this as an update to @Numberknot but with no response therefore I posted this as a separate answer since it's a big difference in bytes between his and my answer.

```
s->s.substring(0,s.length()/2+1);

```

Ungolfed version:

```
interface Func { String foo(String s); }

public class Main
{
    public static void main(String[] args)
    {
        Func s = s->s.substring(0,s.length()/2+1);
    }
}

```
> 0 votes

# Answer
# C#, 26 bytes

```
s=>s.Remove(s.Length/2+1);

```

This removes the end of the string.
> 0 votes

# Answer
# R, 35 bytes

Always late to the party.

```
substr(x<-scan(,""),1,nchar(x)/2+1)

```
> 0 votes

# Answer
# Ruby, 20 bytes

```
->n{n[0,-~n.size/2]}

```

anonymous lambda that returns the first half (rounded up) of a string. The `-~n` is a `1+n` with a higher priority than the division by two, so I don't need any parentheses. Unlike the other Ruby solution, this works on strings with even lengths.

**Usage**:

```
->n{n[0,-~n.size/2]}["abba"]
->n{n[0,-~n.size/2]}["abcba"]
->n{n[0,-~n.size/2]}["a"]

```

**Returns**:

```
"ab"
"abc"
"a"

```
> 0 votes

# Answer
# OIL, 61 bytes

```
5
0
12
0
26
1
26
24
14
div
0
24
1
0
19
8
19
13
27

0
4
0
3

2

```

This uses the `div` from the standard library.
> 0 votes

# Answer
# Japt, 5 bytes

```
¯ÒUÊz

```

Try it here
> 0 votes

---
Tags: code-golf, restricted-source, palindrome
---


# Question
Title: Implement functional programming paradigms
Your company is just getting started on a project, and for the first time you decided to go use a functional programming code-style. However your boss is really diffident and doesn't want to use built-in functions, and requires you to implement yourself the main functions. In particular you need to write the functions: `Map`, `Nest`, `Apply`, `Range`, `Fold` and `Table` in a language on your choice. The boss is a really busy man, and he wants to have the programs as short as possible, so he doesn't waste time reading. He also would like not for you to use loops, therefore you will have a 10% reduction on the byte count for not using loops.

The detailed requirements of the functions are below:

## Map

The `Map` function takes two parameters: `f` and `list` where `f` is a function and `list` is a list of values. It should return the `f` applied to each element of `list`. Therefore it will work as such:

```
Map(f,{a,b,c})

```

returns

```
{ f(a), f(b), f(c) }

```

and

```
Map(f, {{a,b},{b,c}})

```

returns

```
{ f({a,b}), f({b,c})}

```

## Nest

The `Nest` function takes three parameters as well: `f`, `arg`, `times` where `f` is a function, `arg` is its starting argument, and `times` is how many times the function is applied. It should return an expression with `f` applied `times` times to `arg`. Therefore it will work as such:

```
Nest(f, x, 3)

```

returns

```
f(f(f(x)))

```

and

```
Nest(f, {a,b}, 3)

```

returns

```
f(f(f({a,b})))

```

## Apply

The `Apply` function takes two parameters: `f` and `args` where `f` is a function and `args` a list. It should apply `f` to the `args`. Therefore:

```
Apply(f, {a,b,c})

```

returns

```
f(a,b,c)

```

## Range

The `Range` function takes one integer`r` and outputs the integers up to that number. Therefore:

```
Range(5)

```

returns

```
{ 1, 2, 3, 4, 5}

```

## Fold

The `Fold` function takes three parameters `f`, `arg`, `others` where `f` is a function, `arg` is simple parameter, and `others` a list. It will work as such:

```
Fold(f, x, {a, b, c, d})

```

returns

```
f(f(f(f(x,a),b),c),d)

```

## Table

The table functions should take a function `f`, and a parameter called `iterator` in the form: `{iMin, iMax}` where `iMin` and `iMax` are integers. You should apply `f` over the range specified. Therefore:

```
Table(f, {0, 5})

```

returns

```
{f(0), f(1), f(2), f(3), f(4), f(5)}

```

---

I've used the definition of these functions from the Mathematica functional programming page, so head there if you need any more guidance. Note that you will not need to implement all the version of the functions shown in that page, but only those written in this post.

Standard Loopholes are disallowed as usual.

In case your language does not allow functions to be passed as arguments, you need to implement this capability, and add it into your answer. However the byte-count of this operation will not be added to the total.

This is code golf so the shortest code wins. Good luck!!!

# Answer
> 9 votes
# Haskell, ~~many previous byte counts~~ 127 * 0.9 = 114.3 bytes

```
f#(a:b)=f a:f#b;f#x=x
(f&x)0=x;(f&x)i=f$f&x$i-1
i=id
r x=i%(1,x)
(g?x)(a:b)=g(g?x$b)a;(g?x)y=x
f%(a,b)|a>b=[]|1<2=f a:f%(a+1,b)

```

No loops, just recursion.

`#` is map: `(*2) # [1,2,3]` -\> `[2,4,6]`

`&` is nest: `((*2) & 3) 4` -\> `48`

`i` is apply: `i (*2) 7` -\> `14`

`r` is range: `r 4` -\> `[1,2,3,4]`

`?` is fold: `((+) ? 0) [1,2,3,4]` -\> `10`

`%` is table: `(*2) % (2,4)` -\> `[4,6,8]`

As requested an ungolfed version with comments. Note, `&` and `?` are ternary infix operators, which require additional parentheses when called or pattern matched.

```
f # (a:b) = f a : f#b        -- map on a list (a->head, b->tail) is f a in front of mapping f to b
f # x     = x                -- map on the empty list is the empty list
                             -- (non empty lists are caught in the line before)

(f & x) 0 = x                -- nesting zero times is x
(f & x) i = f $ f&x $ i-1    -- nesting i times is f (nesting one time less)

i=id                         -- apply in Haskell is just the identity function

r x = i % (1,x)              -- defined via the "table" of the identity function from 1 to x

(g ? x) (a:b) = g (g?x$b) a  -- folding g into a list (a->head, b->tail) is g applied to (folding g into b) and a
(g ? x) y     = x             -- folding the empty list is x
                             --  again, y must be the empty list, else it would have been handled by the previous line

f % (a,b)
  |a>b       = []                -- if iMin is greater than iMax, the table is empty
  |otherwise = f a : f%(a+1,b)   --  otherwise f a in front of the table with iMin increased by one

```

Thanks to @dfeuer and @Zgarb for some useful hints

# Answer
> 5 votes
# Python 2, 305.1 bytes (-10% ~~376~~ ~~369~~ ~~366~~ ~~349~~ 339 bytes)

```
exec'e=eval;q=len;m=@,l:e("["+"f(l.pop()),"*q(l)+"][::-1]");n=@,x,l:e("f("*l+"*x"+")"*l);r=@:e("r(f-1)+"*(f>1)+"[f]");a=@,a:e("f(a["+`r(q(a))`[1:-1]$",","-1],a[")+"-1])");f=@,x,l:e("f("*q(l)+"x,["+`r(q(l))`[1:-1]$",","-1]),l[")+"-1])");t=@,n,x:e("[f("+`r(x)[n-1:]`$",","),f(")[1:-1]+")]")'.replace("@","lambda f").replace("$",".replace(")

```

When expanded, equivalent to:

```
e=eval;q=len
m=lambda f,l:e("["+"f(l.pop()),"*q(l)+"][::-1]")
n=lambda f,x,l:e("f("*l+"*x"+")"*l)
r=lambda i:e("r(i-1)+"*(i>1)+"[i]")
a=lambda f,a:e("f(a["+`r(q(a))`[1:-1].replace(",","-1],a[")+"-1])")
f=lambda f,x,l:e("f("*q(l)+"x,["+`r(q(l))`[1:-1].replace(",","-1]),l[")+"-1])")
t=lambda f,n,x:e("[f("+`r(x)[n-1:]`.replace(",","),f(")[1:-1]+")]")

```

No loops!

Well, it does a lot of `eval`ing and if your boss can't stand loops, then they'll HATE eval. But, they're going to have to put up with it

A way to do `range` in a lambda is appreciated so I don't have to do any functions (Shudder.).

Explanations:

* `m=lambda f,l:eval("["+"f(l.pop()),"*len(l)+"][::-1]")`
    + Create a string that pops elements from the list, wrap it into a list, reverse it and finally eval it!
* `n=lambda f,x,l:eval("f("*l+"*x"+")"*l)`
    + Manually create the string with the nesting, and eval it!
* `r=lambda i:e("r(i-1)+"*(i>1)+"[i]")`
    + Create a string that when `eval`ed, either returns `[0]` or uses recursion to get the previous results and adds the current index to the list. Evals it.
* `a=lambda f,a:eval("f(a["+`r(len(a))`[1:-1].replace(",","-1],a[")+"-1])")`
    + Uses the range function to get the indexes 1-len(list). Replaces the commas in the list stringified with a way to get the correct index of the list `a`. Evals it!
* `f=lambda f,x,l:eval("f("*len(l)+"x,["+`r(len(l))`[1:-1].replace(",","-1]),l[")+"-1])")`
    + Same as apply except replaces the commas with closing brackets, commas and starting the list index.
* `t=lambda f,n,x:eval("[f("+`r(x)\[n-1:\]`.replace(",","),f(")[1:-1]+")]")`
    + Same as apply and fold except replaces with ending the function and calling the new one. Evals it!

Map, nest, range, apply, fold, table.

Thanks @Zgarb for a lambda for range!

# Answer
> 5 votes
# Javascript ES6, 197 * 0.9 = 177.3 bytes

```
M=(f,l)=>F((a,b)=>[...a,f(b)],[],l)
N=(f,x,n)=>f(--n?N(f,x,n):x)
A=(f,l)=>f(...l)
R=n=>n--?[...R(n),n+1]:[]
F=(f,x,l,n=l.length)=>n--?f(F(f,x,l,n),l[n]):x
T=(f,i)=>([n,x]=i,M(q=>f(q+n-1),R(x-n+1)))

```

### **Map** (`M=(f,l)=>F((a,b)=>[...a,f(b)],[],l)`):

Uses **Fold** to concat the results of `f` applied to every member of `l` onto an empty list. Using built-in functions reduces the this to `M=(f,l)=>l.map(f)` (didn't use it because it seems cheap...?).

### **Nest** (`N=(f,x,n)=>f(--n?N(f,x,n):x)`):

Apply `f` recursively until `n` is decremented to 0.

### **Apply** (`A=(f,l)=>f(...l)`):

Uses the spread (`...`) operator to apply `l` onto `f`.

### **Range** (`R=n=>n--?[...R(n),n+1]:[]`):

Concat `n` to recursive call of **Range** until `n` is decremented to 0.

### **Fold** (`F=(f,x,l,n=l.length)=>n--?f(F(f,x,l,n),l[n]):x`):

Applies the recursive call of **Fold** and the `n`'th element of `l` to `f` until `n` is decremented to 0. Using built-in functions reduces this to `F=(f,x,l)=>l.reduce(f,x)` (again, seemed cheap...).

### **Table** (`T=(f,i)=>([n,x]=i,M(q=>f(q+n-1),R(x-n+1)))`):

First initializes `n` and `x` to iMin and iMax using destructuring (`[n,x]=i`), then uses **Range** to construct the table of values from iMin to iMax. `f` is then applied over the table using **Map** and the result is returned.

# Answer
> 4 votes
# Julia, 181 bytes

No bonus for me; I used loops liberally. Sorry boss, but loops in Julia are efficient!

```
M(f,x)=[f(i...)for i=x]
N(f,x,n)=(for i=1:n x=f(x...)end;x)
A(f,x)=f(x...)
R(n)=(i=0;x={};while i<n push!(x,i+=1)end;x)
F(f,x,a)=(for b=a x=f(x,b)end;x)
T(f,i)=[f(j)for j=i[1]:i[2]]

```

Adding the ellipses after an argument to a function breaks an array, tuple, or what have you into regular function arguments. Otherwise the function will think you're trying to pass an array (or tuple, etc.). It has no effect for single arguments.

Function names:

* Map: `M`
* Nest: `N`
* Apply: `A`
* Range: `R`
* Fold: `F`
* Table: `T`

# Answer
> 4 votes
# Python 3, 218 bytes

The unreadable version:

```
exec("P!:[f(_)for _ in x];Y!,z:Y(f,f(x),z-1)if z else x;T!:f(*x);H!=0:(H(f-1)if~-f else[])+[f];O!,z:O(f,f(x,z[0]),z[1:])if z else x;N!:(N(f,[x[0],x[1]-1])if x[1]-x[0]else[])+[f(x[1])]".replace("!","=lambda f,x"))

```

The (more) readable version:

```
P=lambda f,x:[f(_)for _ in x]
Y=lambda f,x,z:Y(f,f(x),z-1)if z else x
T=lambda f,x:f(*x)
H=lambda f,x=0:(H(f-1)if~-f else[])+[f]
O=lambda f,x,z:O(f,f(x,z[0]),z[1:])if z else x
N=lambda f,x:(N(f,[x[0],x[1]-1])if x[1]-x[0]else[])+[f(x[1])]

```

Going though it one lambda at a time:

### Map function `P`

`P=lambda f,x:[f(_)for _ in x]`
Just a simple iterator. Not much to say here.

### Nest function `Y`

`Y=lambda f,x,z:Y(f,f(x),z-1)if z else x`
Recursing until `z` hits zero, applying `f` every time. The if clause at the end feels clunky; perhaps there is a better way to end the recursion.

### Apply function `T`

`T=lambda f,x:f(*x)`
Python has a nice expansion operator to do all of the heavy lifting for me.

### Range function `H`

`H=lambda f,x=0:(H(f-1)if~-f else[])+[f]`
This one was harder than I was expecting. Ended up taking a recursive approach. Again, the if-else construction takes up a lot of bytes, and I feel it can be improved. Why does it have a dummy `x=0`, you ask? It's so that when I compress it with the `exec`, I can replace `=lambda f,x` instead of just `=lambda f`.

### Fold function `O`

`O=lambda f,x,z:O(f,f(x,z[0]),z[1:])if z else x`
Pretty happy with this one. Just lops off the first element of the array every time it recurses, until there's nothing left.

### Table function `N`

`N=lambda f,x:(N(f,[x[0],x[1]-1])if x[1]-x[0]else[])+[f(x[1])]`
This one is horrible and I'm sure there's room for improvement. Tried to use the range and map functions previously defined for a `map(f,range(x,y))` sort of construction, but without much success. Ended up doing a *terrible* recursive approach which shares some similarity to the range function.

All the lambdas are wrapped up in an `exec` with a `replace` to shorten the byte count significantly.

# Answer
> 4 votes
## tinylisp, 325 * 0.9 = 292.5

The language is newer than the question, but it's not going to win anyway.

```
(d @(q(a a)))(d Q(q((l)(i l(c(@(q q)(h l))(Q(t l)))l))))(d A(q((f a)(v(c(q f)(Q a))))))(d M(q((f l)(i l(c(A f(@(h l)))(M f(t l)))l))))(d N(q((f a x)(i x(A f(@(N f a(s x 1))))a))))(d ,(q((m a b)(i(l b a)m(,(c b m)a(s b 1))))))(d R(q((a)(,()1 a))))(d T(q((f r)(M f(A ,(c()r))))))(d F(q((f a l)(i l(F f(A f(@ a(h l)))(t l))a))))

```

Defines the functions `A` (apply), `M` (map), `N` (nest), `R` (range), `T` (table), and `F` (fold), along with a couple helper functions. `T` expects a list of two integers for its second argument.

Tinylisp doesn't even have any loop constructs; everything is accomplished using recursion. Several of these functions are not tail-recursive, so if you call them on large lists they will probably blow the call stack. They could all be implemented with tail recursion... but it would take more bytes, and this is code golf.

Here's an expanded version with whitespace and real words for names, which should be pretty readable if you're familiar with Lisp. (I've aliased most of the tinylisp builtins except for `q` (quote) and `i` (if).)

```
(d define d)
(define cons c)
(define car h)
(define cdr t)
(define subtract s)
(define less l)
(define eval v)

(define lambda
  (q (()
      (arglist expr)
      (list arglist expr))))

(define list (lambda args args))

(define quote-all
  (lambda (lyst)
    (i lyst
       (cons
         (list (q q) (car lyst))
         (quote-all (cdr lyst)))
       lyst)))

(define Apply
  (lambda (func arglist)
    (eval (cons (q func) (quote-all arglist)))))

(define Map
  (lambda (func lyst)
    (i lyst
       (cons
         (Apply func (list (car lyst)))
         (Map func (cdr lyst)))
       lyst)))

(define Nest
  (lambda (func arg times)
    (i times
       (Apply func
              (list (Nest func arg (subtract times 1))))
       arg)))

(define range*
  (lambda (accumulator a b)
    (i (less b a)
       accumulator
       (range* (cons b accumulator) a (subtract b 1)))))

(define Range
  (lambda (x)
    (range* 1 x)))

(define Table
  (lambda (func iterator)
    (Map func
         (Apply range* (cons () iterator)))))

(define Fold
  (lambda (func arg lyst)
    (i lyst
       (Fold func
             (Apply func (list arg (car lyst)))
             (cdr lyst))
       arg)))

```

Further explanation available upon request.

### Sample output

Uses the REPL environment from my reference implementation. I used `q` (quote) for the unary function and `s` (subtract) as the binary function for these examples, as well as the function `@` (defined in this code) which returns a list of its arguments.

```
tl> [line of definitions goes here]
@
Q
A
M
N
,
R
T
F
tl> (A s (@ 10 7))
3
tl> (M q (@ 1 2 3 4))
((q 1) (q 2) (q 3) (q 4))
tl> (N q 123 4)
(q (q (q (q 123))))
tl> (R 5)
(1 2 3 4 5)
tl> (T q (@ 3 7))
((q 3) (q 4) (q 5) (q 6) (q 7))
tl> (F s 10 (@ 4 3 2))
1

```

# Answer
> 2 votes
# Python 2.x: 450.6 bytes (493 bytes before 10% discount)

Golfed answer:

```
y=len
z=lambda a,b:a.append(b)
_=lambda a:a if a is not None else[]
def M(a,b,c=None):
 c=_(c);d=y(b)
 if d:z(c,A(a,b[0]))
 return M(a,b[1:],c)if d else c
def N(a,b,c):d=A(a,b);return N(a,d,c-1)if c>1 else d
A=lambda a,b:a(*b)if type(b)is list else a(b)
def R(a,b=None):b=_(b);b.insert(0,a);return b if a<=1 else R(a-1,b)
def F(a,b,c):d=a(b,c[0]);return F(a,d,c[1:])if y(c)>1 else d
def T(a,b,c=None,d=None):
 if c is None:c=b[0];d=[]
 z(d,a(c));return T(a,b,c+1,d)if c<b[1]else d

```

This question was fun. I decided to write my functions without using the Python equivalents (though that may have been a valid loophole) and to write the functions as though Python supports tail recursion. To make this work, I used a lot of optional parameters that allow the required calls to still work.

Below I have ungolfed listings for each function.

`Apply`:

```
A = lambda function, arguments: function(*arguments) if type(arguments) is list else function(arguments)

```

`Map`:

```
def M(function, arguments, result=None):
    result = result if result is not None else []
    length = len(arguments)
    if length != 0:
        result.append(A(function, arguments[0]))
    return M(function, arguments[1:], result) if length != 0 else result

```

`Nest`:

```
def N(function, arguments, times):
    result = A(function, arguments)
    return N(function, result, times - 1) if times > 1 else result

```

Note that this function requires that the passed `function` be able to represent multiple arguments variably. Another approach would have been to enforce that the function always received a single list, but that would have required that the passed functions be able to interpret argument lists. There were assumptions either way, so I chose the one that fit the rest of the system better.

`Range`:

```
def R(ceiling, result=None):
    result = result if result is not None else []
    result.insert(0, ceiling)
    return result if ceiling <= 1 else R(ceiling - 1, result)

```

`Fold`:

```
def F(function, initial, rest):
    result = function(initial, rest[0])
    return F(function, result, rest[1:] if len(rest) > 1 else result

```

`Table`:

```
def T(function, iterator, current=None, result=None):
    if current is None:
        current = iterator[0]
        result = []
    result.append(function(current))
    return T(function, iterator, current + 1, result) if current < iterator[1] else result

```

Here is sample output using the following helper functions:

```
square = lambda x: x * x
def add(*args):
    addTwo = lambda a, b: a + b
    if len(args) == 1 and type(args[0]) is list:
        return F(addTwo, 0, args[0])
    else:
        return F(addTwo, 0, args)

>>> M(square, R(10))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> M(add, [R(i) for i in R(10)])
[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
>>> T(square, [0, 10])
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> N(square, 2, 4)
65536
>>> N(lambda *args: F(lambda a, b: a * b, 1, args) if len(args) > 1 else str(args[0]) + 'a', R(5), 10)
'120aaaaaaaaa'

```

# Answer
> 2 votes
## Ceylon, ~~370 * 0.9 = 333~~ 364 * 0.9 = 327.4

Most of those functions are already available in Ceylon's language package (though sometimes with a bit different signature), but we are defining them here like requested in the question.

```
alias I=>Integer;R[]m<A,R>(R(A)g,A[]l)=>f((R[]x,A y)=>x.append([g(y)]),[],l);A n<A>(A(A)g,A a,I t)=>f((A x,I y)=>g(x),a,r(t));R y<A,R>(Callable<R,A>g,A v)given A satisfies Anything[]=>g(*v);I[]r(I i)=>t((j)=>j,[1,i]);A f<A,O>(A(A,O)g,A a,O[]o)=>if(nonempty o)then f(g,g(a,o[0]),o.rest)else a;R[]t<R>(R(I)g,[I,I]i)=>i[1]<i[0]then[]else[g(i[0]),*t(g,[i[0]+1,i[1]])];

```

Actually only two of the functions (`t` and `f`) are actually using recursion (over lists and integers, respectively), the other ones are based on these. (Apply is a bit of an outlier, it doesn't really relate to the others.)

I interpret "List" as Ceylon's Sequential type, which is an immutable ordered (possibly empty) sequence of elements. `[R*]` stands for `Sequential<R>` – for some reason we can also write it `R[]`, which is one byte shorter.

A function type is `Callable<R, A>`, where `A` is a tuple type for the arguments, like `[X, Y, Z]` (i.e. some subtype of `Anything[]`). As a shortcut we can write `R(X,Y,Z)` instead of `Callable<R,[X,Y,Z]>`.

I aliased `Integer` as `I` to save some bytes.

Here is a formatted (and slightly commented) version:

```
// implement functional paradigms
//
// Question: http://codegolf.stackexchange.com/q/58588/2338
// My Answer: http://codegolf.stackexchange.com/a/64515/2338

alias I => Integer;

// map – based on fold.
R[] m<A, R>(R(A) g, A[] l) =>
        f((R[]x,A y) => x.append([g(y)]), [], l);

// nest – based on fold + range, throwing away the second
//        argument in a proxy function.
A n<A>(A(A) g, A a, I t) =>
        f((A x, I y) => g(x), a, r(t));

// apply – this looks quite heavy due to type safety.
//         This uses the "spread operator" *.
R y<A, R>(Callable<R,A> g, A v)
        given A satisfies Anything[] =>
        g(*v);

// range – based on table (using the identity function)
I[] r(I i) =>
        t((j) => j, [1, i]);

// fold – a plain list recursion.
A f<A, O>(A(A, O) g, A a, O[] o) =>
        if (nonempty o) then f(g, g(a, o[0]), o.rest) else a;

// table – an integer recursion.
//        (Not sure why the min/max parameters need
//         to be passed in one argument.)
R[] t<R>(R(I) g, [I, I] i) =>
        i[1] < i[0] then [] else [g(i[0]), *t(g, [i[0] + 1, i[1]])];

```

---

## Using "loops"

Table and Map can be implemented shorter using loops (actually, an sequence comprehension):

```
// map – using a sequence comprehension:
R[] m<A, R>(R(A) g, A[] l) =>
        [for(a in l) g(a)];

// table – map with an integer range.
//        (Not sure why the min/max parameters need
//         to be passed in one argument.)
R[] t<R>(R(I) g, [I, I] i) =>
        m(g, i[0]..i[1]);

```

Though I'm not sure if the use of the `..` operator for the integer range counts as using a built-in function. If this is allowed, the resulting code is this here, length 312:

```
alias I=>Integer;R[]m<A,R>(R(A)g,A[]l)=>[for(a in l)g(a)];A n<A>(A(A)g,A a,I t)=>f((A x,I y)=>g(x),a,r(t));R y<A,R>(Callable<R,A>g,A v)given A satisfies Anything[]=>g(*v);I[]r(I i)=>t((j)=>j,[1,i]);A f<A,O>(A(A,O)g,A a,O[]o)=>if(nonempty o)then f(g,g(a,o[0]),o.rest)else a;R[]t<R>(R(I)g,[I,I]i)=>m(g,i[0]..i[1]);

```

(It could be made even shorter by defining `r(I i) => 1..i`, resulting in score 301. Though that looks even more like cheating.)

If `..` is not allowed, we'll have to implement it again. We can use these implementations for `r` and `t` (with the `m` above):

```
// range – based two-limit range
I[] r(I i) =>
        q(1, i);

// two-limit range implemented recursively
I[] q(I i, I j) =>
        j < i then [] else [i, *q(i + 1, j)];

// table – map with an integer range.
//        (Not sure why the min/max parameters need
//         to be passed in one argument.)
R[] t<R>(R(I) g, [I, I] i) =>
        m(g, q(i[0], i[1]));

```

This results in 348 bytes, better than the completely recursive version, but not after applying the bonus.

# Answer
> 2 votes
# Scala 3 (compile-time), 403 * 0.9 = 362.7 bytes

This works using compiletime black magic.

```
import compiletime.S
type T=Tuple
type E=EmptyTuple
type^[F[_],X<:T]<:T=X match{case h*:t=>F[h]*:(F^t)case _=>X}
type N[F[_],X,T]=T match{case 0=>X case S[t]=>N[F,F[X],t]}
type%[F[_],X]=F[X]
type>[A<:T,X]=X match{case 0=>A case S[e]=>X*:A>e}
type R[X]=E>X
type F[G[_,_],X,L]=L match{case h*:t=>F[G,G[X,h],t]case _=>X}
type-[F[_],I]<:T=I match{case(b,e)=>S[e]match{case`b`=>E case _=>F[b]*:(F-(S[b],e))}}

```

Try it in Scastie

* `^` is Map.
* `N` is Nest.
* `%` is Apply.
* `R` is Range.
* `F` is Fold.
* `-` is Table. NB there is a compiler bug so most functions (type constructors) don't work with my implementation of Table, and only the identity function seems to work.

The first 3 lines are just so long names aren't repeated. `T` and `E` are typealiases we'll need later, and `S` is a type that gives the successor of a singleton type, e.g. `S[1]` becomes `2`. `S` is extremely useful here, as it can not only add 1, but also subtract 1 using match types.

```
import compiletime.S
type T=Tuple
type E=EmptyTuple

```

### Map

```
type ^[F[_], X <: T] <: T = X match {
  case h *: t => F[h] *: (F ^ t)
  case _ => E
}

```

Here, we declare a type `^` that takes 2 parameters, `F` and `X`. The `[_]` after `F` means that `F` is a type constructor of 1 argument, which we'll treat as a function taking a single parameter. `X <: T` means that `X` is a subtype of `T`, which is an alias for `Tuple`. The second `<: T` means that `^` returns a tuple (this is necessary because `^` is recursive).

The body of `^` is a match type. The first case if `X` has at least one element (tuples can be uncons-ed in Scala 3). If so, `X` is destructured into a head `h` and a tail `t`. `F[h]` applies `F` to `h`, and we join that using `*:` to the result of mapping the result of the tuple (`F ^ t` is equivalent to `^[F, t]`). The second case will be reached if `X` is empty, in which case we return `E`, the empty tuple (or rather, the type of an empty tuple).

### Nest

```
type N[F[_], X, T] = T match {
  case 0 => X
  case S[t] => N[F, F[X], t]
}

```

This is more interesting. Here, `F` is the function to repeatedly apply, `X` is the starting argument, and `T` is how many times to apply `F`. If `T` is 0, we simply return `X`. Otherwise, we see if it is the successor of some type `t`. If `T` is a literal type extending `Int`, `t` will be `T - 1`, so the second case is basically calling `N(F, F(X), T - 1)`.

### Apply

```
type %[F[_], X] = F[X]

```

This is boring. It just takes a function `F` and another argument `X` and applies `F` to `X`.

### Range

```
type >[A <: T, X] = X match {
  case 0 => A
  case S[e] => X *: A > e
}
type R[X] = E > X

```

`R` is the Range function, but `>`, a tail-recursive type, does all the heavy-lifting. `>` takes an accumulator tuple `A` and an integer `X`. When `X` reaches 0, it's time to return the accumulator. Otherwise, we use `S` to find an `e` that is `X - 1`. `X` is prepended to the accumulator and `>` is called again with `e`. `R` just calls `>` with an empty tuple as the accumulator to start it off.

### Fold

```
type F[G[_, _], X, L] = L match{
  case h *: t => F[G, G[X, h], t]
  case _ => X
}

```

Here, `G` is a function/type constructor that takes two parameters (like `F[_]` above). `X` is the starting argument, and `L` is the tuple to fold over. If `L` is not empty, the first case will be matched, so we call `F` again with the same function `G`, but with `X` as the result of applying `G` on `X` and the first element of `L`, and with `L` as `L`'s tail.

### Table

```
type -[F[_], I] <: T = I match{
  case (b, e) => S[e] match{
    case `b` => E
    case _ => F[b] *: ( F - (S[b],e) )
  }
}

```

This got a little hairy because of how the second parameter is taken, and it's also affected by a compiler bug (mentioned above). First, we destructure the iterator `I` to get the start and end (here, `b` and `e`). If `b` is greater than `e`, we return an empty tuple (`E`). To test that, we find `e + 1` (`S[e]`) and check if that matches `b`. Otherwise (`case _`), we apply `F` to Imin/`b` and prepend that to the result of calling Table with `b + 1` (`S[b]`) as the new beginning.

# Answer
> 2 votes
# Go, 489 bytes, `int` only

```
func M(f func(int)int,L[]int)(Q[]int){for _,e:=range L{Q=append(Q,f(e))};return}
func N(f func(int)int,s,t int)int{if t<1{return s};return f(N(f,s,t-1))}
func A(f func(...int)int,L[]int)int{return f(L...)}
func R(r int)(O[]int){for i:=1;i<=r;i++{O=append(O,i)};return}
func F(f func(int,int)int,x int,o[]int)int{l:=len(o)-1;if len(o)<2{return f(x,o[l])}else{return f(F(f,x,o[:l]),o[l])}}
func T(f func(int)int,k...int)(O[]int){if len(k)>1{for i:=k[0];i<=k[1];i++{O=append(O,f(i))}};return}

```

Attempt This Online!

Golang is really not designed for concise functional programming. This solution works on `int`s only.

# Go, 492 bytes, generic

```
func M[I,O any](f func(I)O,L[]I)(Q[]O){for _,e:=range L{Q=append(Q,f(e))};return}
func N[I any](f func(I)I,s I,t int)I{if t<1{return s};return f(N(f,s,t-1))}
func A[I,O any](f func(...I)O,L[]I)O{return f(L...)}
func R(r int)(O[]int){for i:=1;i<=r;i++{O=append(O,i)};return}
func F[I any](f func(I,I)I,x I,o[]I)I{l:=len(o)-1;if len(o)<2{return f(x,o[l])}else{return f(F(f,x,o[:l]),o[l])}}
func T[K any](f func(int)K,k...int)(O[]K){if len(k)>1{for i:=k[0];i<=k[1];i++{O=append(O,f(i))}};return}

```

Attempt This Online!

# Answer
> 0 votes
# Groovy (146 Bytes) (146\*90%=131.4)

*P.S. I don't know what you're considering as a 'loop' in this context, I only applied the bonus after I was told to in the comments by OP and will remove if 2-3 additional users say these collection functions and iterators are loops and that I don't deserve the bonus. Also, if you want to call me out on my use of 1..it, please do so and I will rework it / update my bytecount.*

```
m={f,l->l.collect{f(it)}}            // Map
n={f,x,n->n.times{x=f(x)};x}         // Nest
a={f,l->f(l)}                        // Apply
r={1..it}                            // Range (Is this cheating?)
f={f,x,l->l.each{x=f(x,it)};x}       // Fold
t={f,l->(l[0]..l[1]).collect{f(it)}} // Table

```

## Example Input/Output

```
f1={2*it}
f2={a,b,c,d,e->a*b*c*d*e}
f3={a,b->a*b}
l=[1,2,3,4,5]
l2=[1,9]
y=5
x=1
println m(f1,l)
println n(f1,x,y)
println a(f2,l)
println r(y)
println f(f3,x,l)
println t(f1,l2)

```

## Output

```
MAP:   [2, 4, 6, 8, 10]
NEST:  32
APPLY: 120
RANGE: [1, 2, 3, 4, 5]
FOLD:  120
TABLE: [2, 4, 6, 8, 10, 12, 14, 16, 18]

```

Try it yourself: https://groovyconsole.appspot.com/edit/5203951758606336

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


title: Arbitrary-length currying

text:
# Question
Title: Arbitrary-length currying
Write a function, `f`, that takes in a positive integer and returns a function.

The new function returned should be identical to `f`. However, when the "termination call" happens, `f` should instead return the sum of all integers passed.

For example, `g=f(4)` (if `f` is the first function) should set `g` to another function. `h=g(3)` will do the same. However, when you call `h` with no arguments (see below for details), it should output 7, as that is the sum of the previous function arguments. Put another way, `f(3)(4)() == 7`.

Do note this is not the same as `f(3,4)()`.

"Termination call" is one of the following options (your choice):

* call w/o arguments
* null as argument
* any non-positive value

Arbitrary amount of function calls should be supported, there is no predefined limit.

It's guaranteed that total sum will not be bigger than 1'000.

We can assume that there is at least one call is made prior to "termination call".

Your code should not use static, per-program variables, so it should be possible to run the experiment multiple times in the same runtime and observe exactly the same behavior.

Examples:

```
f(1)() == 1
f(4)(2)(7)() == 13
f(4)(2)(7)(5)(2)() == 20

```

# Answer
> 53 votes
## JavaScript (ES6), 18 bytes

```
f=n=>m=>m?f(m+n):n

```

Pass a falsy value to retrieve the sum. Zeros could be allowed for a cost of 2 bytes.

Try it online

**Ungolfed:**

```
f = function(n) {
    return function(m) {
        if (m) {
            return f(m+n);
        } else {
            return n;
        }
    }
}

```

# Answer
> 22 votes
## Haskell (GHC), 118 bytes

This is 98 bytes for the code and 20 bytes for the GHC compiler flag `-XFlexibleInstances`, which enables a type system extension.

```
class F a where f::Int->a
instance F(()->Int)where f n()=n
instance F a=>F(Int->a)where f=(f.).(+)

```

This defines a "function" `f`, which can be called with an arbitrary number of integers followed by the unit `()`, after which it returns an integer. Type annotations are required. Try it online!

## Explanation

Forcing Haskell's strict type system to allow this requires some magic, namely, enabling the GHC extension for flexible typeclass instances. How this works is that `f` is a parametrically polymorphic function restricted by a type class constraint: its type is `F a => Int -> a`. This means that `f` takes an integer and returns a value of type `a`, for any type `a` that belongs to the typeclass `F`. `F` is just the name of the typeclass that provides the function `f`; it's declared on the first line.

The next two lines are two instances of `F` for different types `a`. The second line states that the type of functions from `()` to integers belongs to `F` (where `()` is the unit type whose only member is the value `()`), and the implementation is `f n () = n`; the function returns its first argument. The last line states that if `a` belongs to `F`, then so does the type of functions from integers to `a`: from a function `f :: Int -> a` we can generate another function `f :: Int -> Int -> a`. The implementation is `f m n = f (m+n)` (the code uses combinators to make it shorter), where the `f` on the left is the new one, and the `f` on the right is the old one. This essentially gives `f` a new integer argument, which is added to the next one. Multiple arguments are summed together like this:

```
  f  a1   a2   a3   a4   a5  ()
= f (a1 + a2)  a3   a4   a5  ()
= f (a1 + a2 + a3)  a4   a5  ()
= f (a1 + a2 + a3 + a4)  a5  ()
= f (a1 + a2 + a3 + a4 + a5) ()
=    a1 + a2 + a3 + a4 + a5

```

The `f` on each line has a different type.

Haskell functions are curried automatically, so if you give `f` only integers, you get a function.

# Answer
> 17 votes
# Python 2, ~~42~~ ~~41~~ 36 bytes

This solution will never have an overflow, since Python supports arbitrary-precision integers. Zero is the "special value".

```
f=lambda n:lambda m:m and f(m+n)or n

```

**Try it online**

**Ungolfed:**

```
def f(n):
    def g(m=''):
        return f(m+n)if m<''else n
    return g

```

# Answer
> 14 votes
## Mathematica, 25 bytes

```
f[x_]@y_=f[x+y]
f[x_][]=x

```

Try it online! (Using Mathics.)

It's possible to do three bytes less by porting the JavaScript answer, but I wanted to present a more idiomatic Mathematica solution. The `@` is just a bit of syntactic sugar, which makes the solution equivalent to:

```
f[x_][y_]=f[x+y]
f[x_][]=x

```

So yeah the idea is that in Mathematica you can't just define a function `f[x_]` but you can directly attach a value to a more complicated expression containing `f`, e.g. `f[x_]` being passed another argument. By setting up two definitions for this, we can get the desired behaviour:

* The first definition collapses one `f[x][y]` call into `f[x+y]`, thereby consuming one "call" and adding up the arguments inside. This rule applies until we're left with `f[sum][]`.
* The second definition unpacks this final case by defining the entire thing to evaluate to `sum`.

# Answer
> 14 votes
# C, ~~62~~ 58 bytes, borderline competing

Saved 4 bytes thanks to Kevin! (Still not removing typedef because it's something needed in order to be called.)

```
typedef(*(*B)(_))(_);q;f(x,o,_){x=x?(q+=x,f):(x=q,q=0,x);}

```

The function to call is `f`; you stop calling it and get the result by calling it with a non-positive number like `0`. **Try a test harness online!**

So, as far as I can tell, the only way to "curry" functions that have multiple return types is to do one of the following:

1. Cast the result to a function to tell the compiler you wish to call the result again;
2. or create a `union`/`struct` type that has an `int` and function/self-referential subtypes.

I tried doing (2), but it seemed a bit against the spirit of the question and, quite frankly, nigh undoable. Thus, in keeping with the spirit of the challenge, I have opted for option (1). This requires casting each returned function into a function, that it may be used.

This "currying" syntax looks a bit odd, but is quite similar. To emulate `f(21)(1)`, one would have to write `((B)((B)f(21))(1))(0)`. I defined the `B` type to be a function that takes an integer and returns a pointer to a function that takes an integer. Expanded, this looks like:

```
   ( (B)( (B) f(21) )(1) )(0)
//            f(21)            - call f with 21
//        (B)                  - cast to B, a function pointer
//      (           )(1)       - call with 1
//   (B)                       - cast to a function pointer
// (                     )(0)  - call with 0

```

# Answer
> 8 votes
# C++, 72 bytes

```
#define O(P)operator()(P){return{P+a};}int
struct F{F O(int(m))O()a;}f;

```

This defines a type `F` which acts as the requested function, and a variable `f` of that type to invoke. It's valid as of C++11 and works with online versions of GCC, clang, icc and VC++.

Usage:

```
int main() {
  return f(1)(2)(3)(); // returns 6
}

```

Explanation:

After preprocessing and reformatting, it looks like:

```
struct F {
  F operator()(int(m)) { return{int(m)+a}; }
  int operator()() { return {+a}; }
  int a;
} f;

```

This would normally be written:

```
struct F {
  F operator()(int m) { return {m+a}; }
  int operator()() { return a; }
  int a;
} f;

```

`return a;` and `return {+a};` do the same thing, as unary `+` doesn't change the value, and redundant braces around the return value are allowed. `int m` and `int(m)` do the same thing, as redundant parentheses around a variable name are allowed, including function parameters. `return {m+a};` and `return {int(m)+a};` do the same thing, as a cast of `m` from `int` to `int` does not change its value. These changes get the two `operator()` overloads closer in syntax, allowing a single macro definition to be invoked twice. Picking the right order for the three members allows the first word of the next line (`int`) to be included in the macro definition as well.

# Answer
> 7 votes
# Ruby, 23 bytes

```
f=->n{->m{m ?f[n+m]:n}}

```

Usage:

```
f[1][2][3][nil]
=> 6

```

# Answer
> 6 votes
# C, ~~104~~ 96 bytes

```
#define a(i)s(i)|b
#define b(i)u(i)|c
#define c(i)u(i)|b
b,c,d;s(i){b=c=i;i=d;}u(i){c=b+=i;i=d;}

```

Uses the method from the link that @JulianWolf shared. Last argument must be 0.

Try it online!

# Answer
> 5 votes
# Math.JS, 38 Bytes

```
f(x)=i(x,0)
i(x,y)=x<0?y:j(z)=i(z,y+x)

```

Call it with `f(number_a)(number_b)(...)(negative_number)`

If we're allowed to specify the initial call, 12 bytes (`f(x)=i(x,0)\n`) can be dropped, and it can be called with `i(number_one,0)(number_two)(...)(negative_number)`

Try it!

## Explanation

$$ \begin{align} f(x) & = i(x, 0) \\ i(x, y) & = \begin{cases} y, & \text{if } x \< 0 \\ j(z) = i(z, y+x), & \text{otherwise} \end{cases} \end{align} $$

As shown above, `f(x)` simply calls `i(x,0)`, then, `i(x,y)` returns the value of `y` if `x` is less than 0, or the function `j(z)=i(z,x+y)` otherwise.

# Answer
> 4 votes
## C, ~~232~~ 206 bytes

```
#include<string.h>
#include<stdlib.h>
#define f(X)s(""#X)?0:g
#define g(X)u(""#X)?0:h
#define h(X)u(""#X)?0:g
g=0,h=0;s(char*s){g=h=atoi(s);return 0;}u(char*s){char*a=strlen(s)?s:"0";g=h+=atoi(a);return 0;}

```

This can probably be golfed significantly, but should serve as a proof of concept that C can be used, without any language extensions\*, to solve this problem by calling without arguments rather than with a magic value.

* @hvd has noted that, while this works out of the box using gcc, some of the behavior is not defined in the C standard, meaning that this may not be portable. Use at your own risk!

Ungolfed:

```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define f(X) start("" #X) ? 0 : f0
#define f0(X) update("" #X) ? 0 : f1
#define f1(X) update("" #X) ? 0 : f0

long f0 = 0;
long f1 = 0;

int start(const char *s) {
    f0 = f1 = strtol(s, NULL, 10);

    return 0;
}

int update(const char *s) {
    const char *a = strlen(s) ? s : "0";
    f0 = f1 += strtol(a, NULL, 10);

    return 0;
}

int main() {
    printf("f(1)()          -> %ld\n", f(1)());
    printf("f(1)(2)(0)(3)() -> %ld\n", f(1)(2)(0)(3)());
    printf("f(1)(-2)(3)()   -> %ld\n", f(1)(-2)(3)());
    printf("f()             -> %ld\n", f());

    return 0;
}

```

Compiling and running with `gcc arbitrary-length-currying.c -o arbitrary-length-currying && ./arbitrary-length-currying` outputs (after some warnings)

```
f(1)()          -> 1
f(1)(2)(3)(0)() -> 6
f(1)(-2)(3)()   -> 2
f()             -> 0

```

# Answer
> 4 votes
# 8086 machine code, 27 bytes

```
00000000  bb 00 00 85 c0 74 13 01  d8 be 00 01 89 e7 47 47  |.....t........GG|
00000010  57 b9 1b 00 f3 a4 5b 89  47 01 c3                 |W.....[.G..|
0000001b

```

This machine code must be at address 0x100, and assumes the tiny code model (cs=ds=es=ss). The function location can be changed without costing extra bytes, though. Putting it at offset `0` would save a byte (`xor si,si` instead of `mov si, 0x100`)

**Required calling convention**

This assumes the caller has pre-allocated at least 27 bytes on the stack. It takes a number in `ax`, and returns a function pointer in `bx`. Calling this pointer with `ax=0` terminates the chain, and returns the sum in `bx`.
So for the first call:

```
mov bp, sp
sub sp, 28
mov ax, number_to_add
call function
; new function pointer in bx

```

Then, for each subsequent call:

```
sub sp, 28
mov ax, number_to_add
call bx
; new function pointer in bx

```

To terminate:

```
mov ax, 0
call bx
; result in bx
mov sp, bp

```

---

### Ungolfed (commented disassembly of the machine code):

```
00000000  BB0000            mov bx,0x0      ; 0 is replaced after copying
00000003  85C0              test ax,ax
00000005  7413              jz 0x1a         ; if(ax==0) ret (with value in bx)
00000007  01D8              add ax,bx       ; arg += total
00000009  BE0001            mov si,0x100    ; address of the original: ds:0x100
0000000C  89E7              mov di,sp
0000000E  47                inc di
0000000F  47                inc di          ; dst = sp+2 = above return address
00000010  57                push di
00000011  B91B00            mov cx,0x1b
00000014  F3A4              rep movsb         ; copy the function code.
00000016  5B                pop bx            ; bx = start of copy destination
00000017  894701            mov [bx+0x1],ax   ; update total in the copied code
0000001A  C3                ret               ; with bx = function pointer

```

After calling this with non-zero AX, `bx = sp` and the buffer is filled with a modified copy of the machine code from `function`. The 16-bit immediate in the first instruction holds the total. (It's written by the last instruction before the `ret`.)

`push di` / `pop bx` could be replaced with `mov bx, di` (before `rep movsb`), making it simpler but no savings.

Requiring the caller to pass a pointer to the dst buffer in `di` would save 4 bytes vs. calculating it relative to `sp`.

Making the function start address the same as the function size would save a byte (`mov cx, si`).

# Answer
> 3 votes
# Scala, 58 chars

```
case class f(n:Int){def apply(m:Int)=f(n+m)
def apply()=n}

```

Try it online

### Ungolfed:

```
case class f(n:Int){
  def apply(m:Int)=f(n+m)
  def apply()=n
}

```

### Explanation:

This code defines a `case class` called f with a constructor taking an int. Definind a case class which will generate the equals, hashcode, toString and copy methods, and a companion object with the same name to enable object creation without the `new` keyword.

This class has an overloaded apply method: One takes another integer to add and creates a new object with the updated sum, and one without arguments to get the sum.

In Scala, any object with an apply method can be called like a method, that is `o.apply(x)` can be written as `o(x)`. This is used in the standard libary for arrays, lists, maps and the `Function1` trait implemented by anonymous functions

# Answer
> 3 votes
# C (GCC), 83 bytes

My first C golf! There are a couple of other C solutions, but this one's a bit different. Preprocessor use is purely cosmetic. This approach was first discussed in Conor O'Brien's answer here.

```
#define r union r
t=0;r{int v;r(*f)();};r e;r f(a){t+=a;e.v=a?f:t;t*=a>0;return e;}

```

The terminal value is zero. The return value is a union, so to call the result, use field `f`, and to access the final value, use field `v`, e.g.

```
f(1).f(2).f(3).f(0).v

```

Try It Online

## Limitations

A global variable holds the running total. While this is explicitly disallowed, the submission does support repeated invocations (the total is reset in the terminal call), which seems to be the reason for the ban on global state.

A pointer to `f` is stored to the returned union through the `int` member, so this is clearly not portable. I'm not sure if this works on GCC on all platforms or just on Linux or just on x86 or just with ELF or... If anyone knows any details about this, please comment or send a message!

# Answer
> 3 votes
# APL (Dyalog Classic), ~~48~~ ~~47~~ ~~46~~ 44 32 bytes

```
∇r←(a f)x
r←⍎'(a+x)f'↓⍨-0=x
∇
0f

```

Try it online!

Terminates by passing in zero . Call syntax: `((0 f 1) 2) 0`

-15 bytes thanks to @ngn

Requires `⎕IO←0`

Any golfing tips are welcome!

# Answer
> 3 votes
# Python 3, 39 bytes

```
class f(int):__call__=lambda s,o:f(s+o)

```

Try it online!

Not the shortest (by 3 bytes), but it's different from all previous Python approaches. It works by making a callable `int` subclass. Termination call is optional, but requires a `0` argument if used.

# Answer
> 2 votes
# Pyth, 19 bytes

```
DhdDebR?bh+dbdR$end

```

Try it online!

I'm impressed that Javascript beats Pyth, but then again Pyth is not quite designed to be passing functions.

# Answer
> 2 votes
# Dyvil, 34 bytes

```
infix int apply(i:int,j:int=0)=i+j

```

**Usage**:

```
0() // = 0
0(1)() // = 1
0(1)(2)() // = 3

```

The trailing `()` can be omitted.

**Explanation**:

Defines a juxtaposition operator that takes two ints and adds them. The parameter `j` has the default value `0` to support the call without arguments. The `0` in the examples above is not the name, but a literal.

# Answer
> 2 votes
## C#, 62 bytes

```
dynamic f(int n)=>(System.Func<int,dynamic>)(m=>m<0?n:f(n+m));

```

To end the call pass in a negative number e.g.

```
f(1)(2)(3)(-1) == 6

```

# Answer
> 2 votes
## Perl 5, 36 bytes

```
sub f{my$n=pop;sub{@_?f($n+pop):$n}}

```

---

```
say f(1)->(); # 1
say f(1)->(2)->(3)->(); # 6

```

# Answer
> 2 votes
# Brain-Flak, 6 bytes

Actually I just noticed that since the ToS is a valid return format popping the *0* is not really needed which saves 2 bytes:

```
({{}})

```

Try it online!

## Original submission(s), 8 bytes

Uses `0` as the special value:

```
({{}}{})

```

Try it online!

### Explanation

Given the arguments *a1*, *a2*, … , *an*, *0* the stack initially looks like this:

*an*

*a2*

*a1*

*0*

The code then goes on, pops every *ai*, accumulates them, pops the *0* adds them and pushes the result:

```
(      )  -- push the following value:
 {  }     --   while ToS ≠ 0 (sums the runs):
  {}      --     pop 1 element
     {}   --   pop the remaining 0 & add it

```

---

### Alternative solutions, 8 bytes

Instead of popping the *0* and adding it to the sum, we can also swap stacks since the right one is initially empty:

```
({{}}<>)

```

Try it online!

Using the `-r` flag the *0* is on the top of the stack, so we could pop it first:

```
({}{{}})

```

Try it online!

```
{}({{}})

```

Try it online!

# Answer
> 2 votes
# Java 8, 111 bytes

A lambda from `int` to a function. Calls are terminated by passing zero.

```
i->new java.util.function.Function<Long,Object>(){int t=i;public Object apply(Long x){t+=x;return x<1?t:this;}}

```

Try It Online

## Ungolfed

```
i ->
    new java.util.function.Function<Long, Object>() {
        int t = i;
        public Object apply(Long x) {
            t =+ x;
            return x < 1 ? t : this;
        }
    }

```

Due to an interesting interplay between byte counts of primitive and object integer types, intermediate functions take a `Long` as a parameter, but the total is stored in and returned as an `int`.

## Limitations

The returned function is mutated when called, so, for instance, it's not possible to obtain two integer results without two calls of the lambda. However, the functions returned by separate calls to the lambda are fully independent, so it seems the challenge requirements are met.

Liberal casting is required when constructing expressions that use the lambda. See the TIO for a usage example.

# Answer
> 2 votes
# Rust, 134 bytes

```
|x|{fn b(a:i32,n:i32)->Box<dyn std::any::Any>{if n>0{Box::new(Box::new(move|x|b(a+n,x))as Box<dyn Fn(_)->_>)}else{Box::new(a)}}b(0,x)}

```

Try it online!

In your face, strict type system! Terminates if the input is negative. You do have to downcast the result after every call though (see tio). I took a similar approach to the Math.js solution.

ungolfed:

```
|x| {
        fn b(a: i32, n: i32) -> Box<dyn std::any::Any> {
            if n > 0 {
                Box::new(Box::new(move |x| b(a + n, x)) as Box<dyn Fn(_) -> _>)
            } else {
                Box::new(a)
            }
        }
        b(0, x)
    }

```

Rust's strong type system makes this almost impossible. Fortunately, trait objects come to the rescue. Trait objects erase the type and all associated data except for the trait's implementation. In this instance, I use the `Any` trait, which allows downcasting back into a concrete type. There are some wrinkles because you can't explicitly name the type of closures, so I have to cast the closure into a `Fn` trait object and then recast it into an an `Any` before use.

# Answer
> 2 votes
## PHP7.4 (45 chars)

The superglobal function **$\_ENV** will return an adder function continuously.
After the operations, when no argument is provided **$\_ENV** will return the result.
The function **$\_ENV** is not designed to accept a negative value or no input at all.

```
$_ENV=fn($a)=>fn($b=-1)=>~$b?$_ENV($a+$b):$a;

```

Usage :

```
var_dump($_ENV(1)() == 1);                 // bool(true)
var_dump($_ENV(4)(2)(7)() == 13);          // bool(true)
var_dump($_ENV(4)(2)(7)(5)(2)() == 20);    // bool(true)

```

**Info**: Overriding a superglobal like *$\_ENV* variable isn't recommended.

# Answer
> 2 votes
# Aussie++, ~~98~~ 96 bytes

-2 because I remembered the angle brackets aren't necessary for a single-statement `YA RECKON` body.

```
THE HARD YAKKA FOR f IS(x)<THE HARD YAKKA FOR g IS(y)<YA RECKON y ?BAIL f(x +y);BAIL x;>BAIL g;>

```

Tested in commit 9522366. For the final call, give it `BUGGER ALL` or `YEAH, NAH!` instead of a number.

The general structure is something like

```
function f(x) {
    function g(y) {
        if (y) return f(x + y);
        return x;
    }
    return g;
}

```

Since Aussie++ doesn't have function expressions or anonymous functions yet, it is necessary to put the function declaration and return as separate statements.

# Answer
> 1 votes
# C#, 91 58 bytes

```
dynamic f(int x)=>(Func<int, dynamic>)(y=>y<1?x:f(x + y));

```

# Answer
> 1 votes
## Julia v0.5+, 52 bytes

```
type F n end
F()=0
(f::F)()=f.n
(f::F)(x)=(f.n+=x;f)

```

Call as `F`. This could probably be made a lot shorter by adopting a less OO method, but I always like getting the chance to use this idiom.

If it can be assumed that "at least one call will be made before the termination call", the second line can be removed to save 6 bytes.

# Answer
> 1 votes
# Perl 6, 31 bytes

```
sub f(\n){->$m?{$m??f n+$m!!n}}

```

# Answer
> 1 votes
# PHP, 44 Bytes

An Idea from @user63956

Termination call `0`

```
function f($i){return[$_GET[0]+=$i][$i]?:f;}

```

Online Version

Termination call with `NULL` need a càst `[$i]` to `[+$i]`

# PHP, 47 Bytes

```
function f($i){global$s;return$i?f.!$s+=$i:$s;}

```

Online Version

# PHP, 52 Bytes

Termination call `NULL` or any other value that is false in PHP

```
function f($i){global$s;$i?$s+=$i:print$s;return f;}

```

if the program must terminate after the Output replace `print$s` with `die("$s")` \+ 2 Bytes

Online Version

# Answer
> 1 votes
## Python, 61 bytes

```
f=lambda n="":0if n==""else lambda m="":n if m==""else f(n+m)

```

Much longer than the other Python version, but uses the no-argument syntax rather than a magic number. Can probably be improved upon.

If it can be assumed that "at least one call will be made before the termination call", this can be reduced to **44 bytes**:

```
f=lambda n:lambda m="":n if m==""else f(n+m)

```

# Answer
> 1 votes
# Julia 0.5, 18 bytes

```
!n=k->k>0?!(n+k):n

```

Try it online!

# Answer
> 1 votes
## R, ~~54~~ 52 bytes

```
f=function(x){g=function(y='')'if'(y>'',f(x+y),x);g}

```

*Saved 2 bytes thanks to MickyT!*

Similar to one of the python answers. Ungolfed:

```
f=function(x){
  g=function(y=''){
    if(y>''){
      f(y+x)
      }
      else{x}
  }
  g
}

```

Runs as

```
> f(1)(2)(4)()
[1] 7

```

# Answer
> 1 votes
# Python 3, 63 bytes

```
f=lambda n,l=[]:n and(l.append(n)or f)or sum(l)*(l.clear()or 1)

```

Try it online!

---

Terminates with 0

# Answer
> 1 votes
# C++ (gcc), ~~95~~ 91 bytes

```
struct f{int s;f(int t):s(t){}int operator()(){return s;}f operator()(int t){return s+t;}};

```

Try it online!

# Answer
> 1 votes
# Python, 69 bytes

```
def f(a=0,s=[]):
    if a:
        return lambda b=0:f(b,s+[a])
    return sum(s)

```

# Answer
> 1 votes
# R, 40 bytes

```
f=function(x)function(y)`if`(y,f(x+y),x)

```

0 acts as the stop value here. For two more bytes, we can omit it.

The problem is that R lacks a concise built-in lambda. But if we add one, we can get the code to **26 bytes**:

```
f=x->(y->`if`(y,f(x+y),x))

```

(Yes, that’s valid R. It just needs an import.)

# Answer
> 1 votes
**PowerShell, 86 bytes**

```
$f={$n=$args[0];$f=(gv f).value;{if($args){&$f($args[0]+$n)}else{$n}}.getnewclosure()}

```

Try it online!

**Test code:**

```
&(&(&(&(&(&$f 4)2)7)5)2)

```

**Output:** 20

# Answer
> 1 votes
# Octave, 39 bytes

```
function r=f(n)r=@(m)merge(m,f(m+n),n);

```

\*Argument of the termination call is 0.

Try it online!

*`endfunction` required to add some other codes.

# Answer
> 1 votes
# Lua, 89 bytes

```
function f(...)n,p=...p=p or 0 return n and loadstring("return f(...,"..n+p..")")or p end

```

Well it's not exactly the shortest I see (Lua never is), but it was an interesting challenge. Had a lot of attempted arithmetic on a function and attempted to call a number along the way before the aha moment.

As a slight bonus though, it does work with non-positive numbers since nil and false are the only false values in Lua. In many golfing challenges, 0 ~= false is a drawback but not here!

# Answer
> 1 votes
# k, 22 bytes

Call with a null value to terminate

```
{$[^y;+/x;.z.s[y,x]@]}

```

Example:

```
k)f:{$[^y;+/x;.z.s[y,x]@]}
k)g:f[3]
k)h:g[4]
k)h[0N] //0N is null integer in k
7

```

# Answer
> 1 votes
## Clojure, 29 bytes

```
(defn f[n]#(if %(f(+ n %))n))

```

Example:

```
(for [f (->> [3 2 1 4 10] (reductions (fn [f val] (f val)) f) rest)]
  (f nil))
(3 5 6 10 20)

```

# Answer
> 1 votes
**C#, 53 bytes**

```
Func<int,dynamic>f(int i)=>m=>m<0?(dynamic)i:f(m+i);

```

Any negative number can act as the stop value

```
int j = f(5)(3)(4)(-1); // j = 12

int j = f(-1); // Compile Error, must be 2 or more calls

```

# Answer
> 1 votes
# Attache, 20 bytes

```
{If[_,$&Sum[__],_2]}

```

Try it online!

## Explanation

```
{If[_,$&Sum[__],_2]}
{                  }    lambda, taking parameters stored in `__`
 If[_,            ]     If the first parameter `_` is truthy (nonzero):
      $                    return this function
       &                   bonded with
        Sum[__]            the current running sum
               ,        otherwise:
                _2         return the sum

```

Since `(f&n)[x]` is equivalent to `f[x, n]`, this will continue returning itself with the updated sum until `n = 0`.

If you want computation to occur after the final `0`, then one could do this for 28 bytes:

```
{If[_,Fold[`&,$'__],Sum!__]}

```

This is much the same thing, except we use `Fold[`&,$'__]` to bond `$` with each individual argument.

# Answer
> 1 votes
# Nim, 135 bytes

```
import sugar
type X=object
 case t:int8
 of 0:i:int
 else:f:int->X
func s(x:int):int->X=(y:int)=>(if y<0:X(t:0,i:x)else:X(t:1,f:s x+y))

```

Try it online!

Like the JavaScript answer, but with type safety.

# Answer
> 1 votes
## Google Sheets, 39

Based on the explanation here

Named functions:

| name | args | body |
| --- | --- | --- |
| F | a | `G(0,a)` |
| G | a, b | `IF(b>0,LAMBDA(c,G(a+b,c)),a)` |

Score: 34 (body text) + 2 (names) + 3 (args) = 39

### Example

Termination call arg is any non-positive number:

```
=F(2)(4)(0)

```

gives 6.

# Answer
> 0 votes
# Go, 87 bytes

```
func f(x int)func(int)any{g:=func(y int)any{if y<1{return x+y}
return f(x+y)}
return g}

```

Attempt This Online!

Stopping value is 0.

This works because the `any` in Go represents all types, at the expense of every call after the 2nd needing to be cast with `.(func(int)any)`, like `f(3)(4).(func(int)any)(0)`.

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


# Question
Title: Count how many numbers are divisible by perfect numbers in a given range
Given two arbitrary integers \\$a\\$ and \\$b\\$, count how many numbers are divisible by perfect numbers in that given range (\\$a\\$ and \\$b\\$ both are inclusive).

> In mathematics, a perfect number is a positive integer that is the sum of its proper positive divisors, that is, the sum of the positive divisors excluding the number itself.Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself), or \\$σ(n) = 2n\\$.

**Input:**

```
1 100

```

**Output:**

```
18

```
* Use stdin and stdout for Input/Output
* **Your code must handle big integers, so it is not good enough to hard-code a list of perfect numbers.**
* Shortest code wins

# Answer
> 3 votes
## Perl 6, ~~106~~ 103 characters

```
my ($a,$b)=get.words;(($a..$b).grep: *%%any ($a..$b).grep: {$^n==[+] ($^n%%$_&&$_ for 1..^$^n)})[*.say]

```

There's a lot of syntax here, so hopefully this explanation helps at least a little to someone who knows a bit of Perl 5 syntax, though I won't explain every detail:

Finds all the perfect numbers in the range $a..$b: `($a..$b).grep: {$^n==[+] ($^n%%$_&&$_ for 1..^$^n)}` (explained below). It then chooses all the numbers in the range $a..$b which are divisible (`%%`) by any of the perfect numbers it had found: `(%a..%b).grep: * %% any …`.

The final `(…)[*.say]` abuses the fact that any code (in this case `*.say`, which prints its argument and a newline) passed to the `[…]` postfix will be given the list's length as its argument (so that one can, e.g., use the idiomatic `@array[*-1]` to get the last element of `@array`). This means that the `(…)[*.say]` here has the same effect as `say (…).elems`.

The part that finds all the perfect numbers in the range does so by returning only those numbers which are equal (`$^n ==`) to the sum of their divisors. `[+]` adds together the values following it, `for 1..^$^n` iterates over all numbers 1 to $^n-1 and assigns $\_ to them, and `$^n %% $_ && $_` returns $\_ if $^n is divisible (`$^n %% $_`) by $\_, or else `False`, thus creating a list that consists of the proper divisors of $^n and `False` objects, which numify to 0 when all the values are added together by `[+]`.

Perl 6 uses arbitrary sized integers, so, if you have the resources and the time, it could technically compute for big integers

# Answer
> 3 votes
# Mathematica - 117

Naive approach, linear for the range size

```
With[{p=#(#+1)/2&/@Select[2^Range@@Floor@Log2@Sqrt@#-1,PrimeQ]},Length@Select[Range@@#,Or@@Divisible[#,p]&]]&@Input[]

```

The correct way would be constructing numbers from the perfect numbers that are in the given range of course.

# Answer
> 3 votes
# C, ~~125~~120

```
a,b,c,p[4]={6,28,496,8128};main(i){for(scanf("%d%d",&a,&b);a<=b;a++)for(i=0;i<4;)if(a%p[i++]==0)c++,i=4;printf("%d",c);}

```

A little more readable:

```
a,b,c=0,i,p[4]={6,28,496,8128};
main()
{
    for(scanf("%d%d",&a,&b);a<=b;a++)
        for(i=0;i<4;)
            if(a%p[i++]==0)
            {
                c++;
                i=4;
            }
    printf("%d",c);
}

```

This works with signed 32bit integers, up to **2^31-1=2147483647**.

# C, ~~212~~209

```
#include<stdint.h>
uint64_t a,b,c,p[8]={6,28,496,8128,33550336,8589869056,137438691328,0x1fffffffc0000000};main(i){for(scanf("%lld%lld",&a,&b);a<=b;a++)for(i=0;i<8;)if(a%p[i++]==0)c++,i=8;printf("%lld",c);}

```

Should work up to **2^64-1=18446744073709551615**.

# Answer
> 3 votes
# Haskell - 157

```
c x=x==sum[i|i<-[1..x-1],mod x i==0]
d x=any((0==).mod x)$takeWhile(<=x)(filter c[2..])
main=do m<-getLine;n<-getLine;print$length(filter d[read m..read n])

```

Can work with arbitrarily large numbers given respectively large time.
Input is given on 2 lines.

# Answer
> 2 votes
## Python 3 \[166 bytes\]

```
a,b=map(int,input().split());print(len(set([n if n%p==0 else 0 for p in [x for x in range(a,b) if sum(y for y in range(1,x) if x%y==0)==x] for n in range(a,b+1)]))-1)

```

More readable:

```
// STDIN => a, b
a, b = map(int, input().split())

// list of perfect numbers
perfect = [x for x in range(a, b) if sum(y for y in range(1, x) if x % y == 0) == x]

// length(number % [any perfect number] == 0) => STDOUT
print(len(set([n if n % p == 0 else 0 for p in perfect for n in range(a, b + 1)])) - 1)

```

Here the list of perfect numbers is calculated inline but may be set statically. The number range should be bound by the machine's word size.

<sub>While this algorithm is deadly slow and takes ages for working with big numbers, it is at least short `:)`</sub>

# Answer
> 2 votes
# Jelly, 10 bytes

```
rÆD=Æṣ$§TL

```

Try it online!

Requiring space separated STDIN input bumps the byte count up to 15 bytes

## How it works

```
rÆD=Æṣ$§TL - Main link. Takes a on the left and b on the right
r          - Yield [a, a+1, ..., b-1, b]
 ÆD        - Generate the divisors of each
      $    - Over each list of divisors, d:
    Æṣ     -   Generate the proper divisor sum of each value in d
   =   §   -   Count how many are equal to their proper divisor sum
             This maps numbers with perfect to divisors to a non-zero value
             and those without to 0
        TL - Count the number of non-zero elements

```

# Answer
> 0 votes
# Perl 5 `-MList::Util=sum,any -pl`, 77 bytes

```
$"=$_,$\+=any{$"%$_==0}grep{//;2*$_==sum grep{$'%$_==0}1..$_}2..$"for$_..<>}{

```

Try it online!

Ungolfed:

```
$_ = ; # implicit by -p command line switch
for$_($_..){ # loop over the range from $_ to the next input
   $"=$_;                           # store a copy of the current number ($_) so it can be used in sub-loops
   $\+=                             # counter for number of perfectly divisible numbers found
      any{$"%$_==0}                 # check if the current number ($") is evenly divisible by a:
         grep{//;2*$_==             # PERFECT NUMBER: a number where twice the number equals
            sum grep{$'%$_==0}1..$_ #                 the sum of the numbers which divide it evenly
         }2..$"                     # that exists in range of 2 to the current number
}
print$\; # implicit by -p command line switch
```

# Answer
> 0 votes
# Vyxal, 11 bytes

```
ṡƛ'∆K=;Ḋa;∑

```

Try it Online!

9 bytes with `s` flag

12 bytes accounting for space seperated inputs

## Explained

```
ṡƛ'∆K=;Ḋa;∑
ṡƛ       ;  # Over each item x in the range [input a, input b]
  '∆K=;     #   Keep items from the range [1, x] that are perfect numbers
       Ḋa   #   And is x divisible by any of those perfect numbers?
          ∑ # Sum the number of numbers that are divisible by a perfect number

```

---
Tags: code-golf, number-theory
---


title: Generate a Tiefling's Traits

text:
# Question
Title: Generate a Tiefling's Traits
A Tiefling is a character race, from Dungeons and Dragons, that has this list of possible traits:

* small horns
* fangs or sharp teeth
* a forked tongue
* catlike eyes
* six fingers on each hand
* goat-like legs
* cloven hoofs
* a forked tail
* leathery or scaly skin
* red or dark blue skin
* cast no shadow or reflection
* exude a smell of brimstone.

---

Given a list of Tiefling traits as input, randomly pick 1d4 + 1 (**uniform distribution from 2-5**) traits from that list and output them.

This challenge uses the standard definition of random, and the number and trait selection from the list must *separately* conform to definition 1 from here:

* All possible \[numbers\] should be produced with the same probability;
* All possible \[traits\] should be produced with the same probability;

You are allowed to pick randomly from the list by first shuffling it and taking the top 1d4+1 traits, so long as the shuffle does not favour any item in the list. Repeat selections of the same trait are not allowed.

Here is a non-golfed implementation in Javascript:

```
const dice = (n, s, a, doSum) => {
  const die = () => Math.floor(Math.random() * s) + 1;
  const dieResults = Array.from(Array(n)).map(each => {
    return die();
  });
  const sum = dieResults.reduce((sum, curr) => sum + curr + a, 0);
  // logging not required here
  console.log(`rolled '${dieResults.join(` + ${a}, `)} + ${a}${doSum ? ` = ${sum}`:''}'`);
  return doSum ? dieResults.reduce((sum, curr) => sum + curr + a, 0) : dieResults.map(each => each + a);
};

const shuffleSlice = (num, array) => array
  .map(value => ({
    value,
    sort: Math.random()
  }))
  .sort((a, b) => a.sort - b.sort)
  .map(({
    value
  }) => value).slice(0, num);

// you can take the list as a string or an actual list
const tieflingTraits = "small horns; fangs or sharp teeth; a forked tongue; catlike eyes; six fingers on each hand; goat-like legs; cloven hoofs; a forked tail; leathery or scaly skin; red or dark blue skin; cast no shadow or reflection; exude a smell of brimstone".split(/;\s+/);

// calling the function
console.log(shuffleSlice(dice(1, 4, 1, true), tieflingTraits))

// outputs like
//  ['goat-like legs', 'cast no shadow or reflection', 'a forked tongue']
```

This is so shortest in bytes wins.

# Answer
# Factor \+ `dice`, 22 bytes

```
[ ROLL: 1d4+1 sample ]

```

Try it online!

A quotation (anonymous function) that takes a list of strings as input and outputs a uniformly random sample of 1d4+1 items of said list.
> 7 votes

# Answer
# Retina, 22 bytes

```
?O`
,3G`¶
?&0A`¶
?&0A`

```

Try it online! Explanation:

```
?O`

```

Uniformly shuffle the input.

```
,3G`¶

```

Keep the first four (0-indexed) newline characters, which also ends up keeping the first five lines.

```
?&0A`¶

```

50% chance to delete the first newline character including the first two lines.

```
?&0A`

```

50% chance to delete the first line.
> 5 votes

# Answer
# Jelly,  ~~7~~  6 bytes

```
Ẋṫ4XN¤

```

A monadic Link that accepts a list of lists of characters and yields another with 2-5 random entries.

**Try it online!**

### How?

```
Ẋṫ4XN¤ - Link: list, A
Ẋ      - get a shuffled copy of A
     ¤ - nilad followed by link(s) as a nilad:
  4    -   four
   X   -   random choice from 1-4
    N  -   negate
 ṫ     - tail (the shuffled copy) from (that) 1-indexed index

```
> 5 votes

# Answer
# Raku, 18 bytes

```
*.pick(pick 2..5:)

```

Try it online!

`pick 2..5:` picks a random number from 2 to 5, then gives that as an argument to the `pick` method on the input list, randomly choosing that many elements from it.
> 5 votes

# Answer
# Python (Full program), 58 bytes

* -1 byte thanks to @The Fifth Marshal

```
from random import*;print(sample([*open(0)],randint(2,5)))

```

Attempt This Online!

# Python (Function), 51 bytes

* -7 bytes thanks to @Jonathan Allan

```
lambda a:sample(a,randint(2,5))
from random import*

```

Attempt This Online!
> 4 votes

# Answer
# Goruby, 16 bytes

```
->a{a.s rn 2..5}

```

Attempt This Online!

# Ruby, 23 bytes

```
->a{a.sample rand 2..5}

```

Attempt This Online!
> 4 votes

# Answer
# Japt, ~~6~~ ~~5~~ 7 bytes

```
ö¬o2+4ö

```

Try it

```
ö¬o2+4ö     :Implicit input of array
ö¬          :Random permutation
  o         :Pop & return this many elements
   2+       :  Two plus
     4ö     :  Random integer in range [0,4)

```
> 4 votes

# Answer
# Excel (ms365), 52 bytes

```
=TAKE(SORTBY(A1:A12,RANDARRAY(12)),RANDBETWEEN(2,5))

```
> 4 votes

# Answer
# Bash \+ coreutils, 20

```
shuf -n$[RANDOM%4+2]

```

Try it online!
> 3 votes

# Answer
# Charcoal, 21 bytes

```
ＷＳ⊞υι≔⟦⟧θＦ⁺²‽⁴⊞θ‽⁻υθθ

```

Try it online! Link is to verbose version of code. Explanation:

```
ＷＳ⊞υι

```

Read in the list of possible traits.

```
≔⟦⟧θ

```

Start with no traits selected.

```
Ｆ⁺²‽⁴

```

Repeat `2-5` times uniformly randomly.

```
⊞θ‽⁻υθ

```

Pick a trait uniformly randomly from the list of traits not already picked.

```
θ

```

Output the final list of picked traits.
> 2 votes

# Answer
# PowerShell, 25 bytes

Input comes from the pipeline.

```
random -c(random -mi 2 6)

```

Try it online!

**Ungolfed:**

```
Get-Random -Count (Get-Random -Minimum 2 -Maximum 6)

```

Straightforward; Get-Random with "-Count x" will randomly select x objects from the pipeline input.

The verb "Get-" can (in dire situations as code golf) be dropped from cmdlet names *\<Verb\>-\<Noun\>*; if PS finds no program or cmdlet named "\<*noun*\>", it will add "Get-" and try to find that. **Disclaimer** Use this for golfing only, never in normal scripts; it'll slow down the script (because it will try to find *\<noun\>*.exe in the path first every time), and may start unrelated programs on other systems.
> 2 votes

# Answer
# MathGolf, ~~17~~ 14 bytes

```
mÅvαá├mÅ~;3w⌠<

```

Try it online.

I really hate this language sometimes.. -\_- This should in theory have been `áv3w⌠<` (6 bytes), but due to a number of bugs, it ended up as 17 bytes instead.

**Explanation:**

*Explanation of the intended solution, and why it didn't work due to bugs:*

```
á       # Sort the (implicit) input-list by:
 v      #  A random integer in the range [-2147483648,2147483647]
  3w    # Push a random integer in the range [0,3]
    ⌠   # Increase it by 2 (to have the range [2,5] instead)
     <  # Only keep that meany leading items from the shuffled list
        # (after which the entire stack is output implicitly as result)

```

*Bugs:*

1. ~~MathGolf changes all spaces in string inputs to `", "` (try it online with explicit print). This bug is likely because MathGolf supports multiple inputs both separated by commas and spaces, so when a string or string-list is used that contains spaces, it incorrectly splits them, before interpreting the splitted string as string again..<br>This is fixed with the leading `mÆ',-` (only works because the input-strings are all without commas)~~
EDIT: Apparently using `'` quotes for strings instead of `"` fixes this issue.
2. MathGolf's sort-by builtin `á` apparently evaluates its body once in some cases, because `áv` and `áf` both result in an unsorted list and act similar as `á1` would.
This is fixed by replacing it with `mÅvαá├mÅ~;`:

```
m       # Map over the (implicit) input-list,
 Å      # using 2 characters as inner code-block:
  v     #  Push a random integer from the range [-2147483648,2147483647]
   α    #  Pair the string and random integer together
á       # After the map: sort by:
 ├      #  The left (a third bug, should have been `┤` for right..) item: the random integer
m       # After the sort-by: map again,
 Å      # using 2 characters as inner code-block:
  ~     #  Dump the string and random integer to the stack
   ;    #  And discard the random integer

```

After which we can use the `3w⌠<` explained above to finish the program.
> 2 votes

# Answer
# 05AB1E, 7 bytes

```
.rY5ŸΩ£

```

Very straight-forward, but can't find anything shorter. (I initially read the challenge description wrong as 1-4 random outputs, which would be possible in 4 bytes. 2-5 however is a bit longer.)

Try it online.

**Explanation:**

```
.r       # Randomly shuffle the (implicit) input-list
  Y5Ÿ    # Push a list in the range [2,5]: [2,3,4,5]
     Ω   # Pop and get a random value from this list
      £  # Only leave that many items from the shuffled list
         # (after which the result is output implicitly)

```
> 1 votes

# Answer
# J-uby, ~~35~~ 24 bytes

Port of my Ruby answer.

```
~:sample&(-:rand^(2..5))

```

Attempt This Online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 23 bytes (15 chars)

```
{⍵[(≢⍵)?⍨1+?4]}

```

Explanation:

```
{              } ⍝ defun:
          1+?4   ⍝ roll a d4, add 1
   (≢⍵)?⍨        ⍝ generate random indices
 ⍵[           ]  ⍝ index them into ⍵ to get final traits

```
> 0 votes

---
Tags: code-golf, random
---


title: Do I have permission?

text:
# Question
Title: Do I have permission?
# The Challenge

Given a string indicating the symbolic notation of UNIX permission of a file and its ownership (user ID and group ID), decide whether a given user `A` has permission to read / write / execute it.

*Related.*

## Permissions in UNIX system

In UNIX, every file has three classes of permissions (**user**, **group** and **others**) and ownership, including which user and which group it belongs to.

The symbolic notation consists of ten characters. The first character is not important in this challenge. The remaining nine characters are in three sets of three characters, representing permissions of user, group and others class. Characters in each set indicates whether reading / writing / executing is permitted. If permitted, it will be `r`, `w` or `x`. Otherwise, it will be `-`.

Note that *setuid*, *setgid* and *sticky bit* may change the third character of each set to `s`, `S`, `t` or `T`. Here's a simple rule: if the character is lowercase letter, then the permission is set; otherwise, it is not.

(For the details of symbolic notation of permissions, please refer to here.)

Every user has its user ID, and every group has its group ID. All IDs will be non-negative integers. A user will belong to at least one group. If a user `A` want to get access to a file, the system will check their permissions as follows:

* If the file belongs to user `A`, check the permissions of **user** class.
* If the file doesn't belong to `A`, but `A` belongs to the group which the file belongs to, check the permissions of **group** class.
* Otherwise, check the permissions of **others** class.

However, there is one exception: if the user ID is 0 (superuser), they have permission to do **anything**!

# Specifications

* Your program / function should take these as input in any reasonable format:
    + Permissions **in symbolic notation**.
    + User ID and group ID which the file belongs to.
    + The user ID of `A`, and a list of group IDs which `A` belongs to.
    + Type of access. You can use any three different one-digit or one-character values for read, write and execute.
* Return / output a truthy value if `A` has permission to access the file, or a falsy value if not.
* You can assume that the first character of the notation will always be `-` (regular file).
* This is , so the shortest in bytes wins!

# Test Cases

The format here is `[permissions, user ID of file, group ID of file, user ID of A, group IDs of A, type(r/w/x)]`.

```
[-rwx------, 13, 15, 13, [15, 24], r]: True   # user
[-rwxr-xr-x, 13, 24, 24, [15, 24], w]: False  # group
[-rwxr-Sr-T, 13, 15, 24, [15, 35], x]: False  # group
[-rwsr-xr-t, 13, 15, 24, [24, 35], x]: True   # others
[----------, 13, 15, 0, [0, 1, 2], r]: True   # superuser
[----------, 13, 15, 1, [0, 1, 2], r]: False  # others
[----rwxrwx, 13, 15, 13, [15, 24], r]: False  # user

```

# Answer
# JavaScript (ES6), ~~61~~ ~~51~~ 50 bytes

Takes 6 distinct parameters as input, in the order described in the challenge. Expects the last parameter to be `1` for *read*, `2` for *write* or `3` for *execute*. Returns `0` or `1`.

```
(p,u,g,a,G,P)=>!a|p[u-a?6-3*G.includes(g)+P:P]>'Z'

```

### Test cases

```
let f =

(p,u,g,a,G,P)=>!a|p[u-a?6-3*G.includes(g)+P:P]>'Z'

//            p             u   g   a   G          P
console.log(f('-rwx------', 13, 15, 13, [15, 24],  1)) // True  (user)
console.log(f('-rwxr-xr-x', 13, 24, 24, [15, 24],  2)) // False (group)
console.log(f('-rwxr-Sr-T', 13, 15, 24, [15, 35],  3)) // False (group)
console.log(f('-rwsr-xr-t', 13, 15, 24, [24, 35],  3)) // True  (others)
console.log(f('----------', 13, 15,  0, [0, 1, 2], 1)) // True  (superuser)
console.log(f('----------', 13, 15,  1, [0, 1, 2], 1)) // False (others)
console.log(f('----rwxrwx', 13, 15, 13, [15, 24],  1)) // False (user)
```
> 7 votes

# Answer
# Python 2, ~~76~~ ~~70~~ ~~67~~ ~~63~~ ~~59~~ ~~58~~ ~~56~~ ~~55~~ ~~52~~ ~~49~~ 48 bytes

```
lambda p,u,g,A,G,t:A*'_'<p[~(u==A)*3*(g in G)-t]

```

Try it online!

Takes type as `3` for read, `2` for write ,and `1` for execute
> 3 votes

# Answer
# Java (OpenJDK 8), 60 bytes

```
(p,u,g,U,G,t)->U<1|p.charAt(t+(u==U?0:G.contains(g)?3:6))>90

```

Try it online!

The mapping for the type is the following: `1` means `r`, `2` means `w` and `3` means `x`.
> 1 votes

# Answer
# Pyth, ~~22~~ 21 bytes

```
|!Q}@@c3tw*nEQ-2}EEEG

```

Try it online. Test suite.

Takes input as six lines:

```
user id
permissions
file user id
file group
user groups
permission (0 = read, 1 = write, 2 = execute)

```

### Explanation

```
|!Q}@@c3tw*nEQ-2}EEEG     Implicit: read user id to Q
 !Q                       True if user id is 0, false otherwise
|                         If true, just return it
         w                Read permission string
        -                 Omit first -
      c3                  Split in 3 parts
            E             Read file user id
           n Q            See if it doesn't equal Q
                          -> False (0) if user matches, true (1) otherwise
                 E        Read file group
                  E       Read user groups
                }         -> True (1) if group matches, false (0) otherwise
              -2          Subtract from 2
                          -> 1 if group matches, 2 otherwise
          *               Multiply the two numbers
                          -> 0 if user matches, 1 if group matches, 2 otherwise
     @                    Take correct part of permission string
    @                     Take correct character of that part
   }                G     See if it is in lowercase alphabet

```
> 1 votes

# Answer
# Go, 284 bytes

```
import(."unicode";."golang.org/x/exp/slices")
func X(P string,f,g,u,a int,s[]int)int{P=P[1:]
p,i:=0,0
for;i<3;i++{for j:= 0;j<3;j++{e:=0
if IsLower(rune(P[3*i+j])){e++}
p|=e<<(3*i+j)}}
if u==0{return 1}
p>>=a
if f==u{return p&1}else if Contains(s,g){return p>>3&1}else{return p>>6&1}}

```

Attempt This Online!

`rwx` is `012`.

### Explanation

```
import(."unicode";."golang.org/x/exp/slices")
func X(P string,f,g,u,a int,s[]int)int{
// load the perms
P=P[1:] // strip the leading char
p,i:=0,0
// for all chars in the string...
for;i<3;i++{for j:= 0;j<3;j++{
// if it's lowercase, bit-or it with its respective location in the perms variable
e:=0
if IsLower(rune(P[3*i+j])){e++}
p|=e<<(3*i+j)}}
// the perm variable is stored as
// 876543210
// xwrxwrxwr
// -o-|g|-u-
// other, group, user, with the lowest bit on the right.
if u==0{return 1} // superuser
p>>=a // constant offset based on the access type
if f==u{
// user's file
return p&1
}else if Contains(s,g){
// user's group's file
return p>>3&1
}else{
// other
return p>>6&1
}}

```

## Directly accessing the string, 145 bytes

```
import."golang.org/x/exp/slices"
func X(P string,f,g,u,a int,s[]int)bool{k:=0
if f==u{}else if Contains(s,g){k=3}else{k=6}
return u<1||P[a+k]>90}

```

Attempt This Online!

Based on @Olivier Grégoire's answer, and `rwx` is also `123` here.
> 1 votes

# Answer
# C (GCC), 117 bytes

```
f(p,u,g,U,G,t,o)char*p;int*G;{t=t-'r'?t-117:1;if(o=u-U?6:0)for(;*G;++G)if(g==*G)o=3;return U==0|p[t+=o]>96&p[t]<123;}

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, decision-problem
---