[Question]
      [
Write a piece of code that takes a string as input, and outputs a piece of code in the **same language** that, when run, will output the initial input string.
It must be able to handle any combination of characters A-Z, a-z, and 0-9.
Example in Python:
```
import sys
print "print('" + sys.argv[1]  + "')"
```
Given the input of `testing123`, it will return `print('testing123')`.
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes will win.

[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 30 bytes
```
'":v
~\#[
<v">:#,_""#
<>4k,'@,
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XV7Iq46qLUY7msilTsrNS1olXUlLmsrEzydZRd9D5/78ktbgkMy/d0MgYAA "Befunge-98 (PyFunge) – Try It Online")
This prints a program in the form `"...ihgfedcba">:#,_@`, which prints `abcdefghi...`
### Explanation
The code boils down to:
```
'":v    Push 2 quotation marks
~\#[    Get input and swap the top 2 items until EOF.
            Because every time we put a new value from input on the stack we also swap,
            the second quotation mark will float to the top, surrounding the input.
   >:#,_       A standard "print until the top is 0" loop
        ""#    Pushes a space, which is fine, since we control how much we print later
<v">:#,_"      When the IP gets reversed, we actually push the loop backwards onto
               the stack. This lets us print it later, instead of having to hardcode it.
 >4k,'@,       Prints 5 characters, being the printing loop from before, along with a @
<     @,       Prints an extra space, but it doesn't matter, and ends the program
```
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
'echo',quote
```
[Try it online!](https://tio.run/##y/r/P81WT0E9NTkjX12nsDS/JPU/iO2QZq0Xb6jg46ZTXJKSmadg@L8ktbgkMy/d0MiYiys5sUS9WKEgsbwYAA)
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 12 bytes
```
$><<"p'#$_'"
```
[Try it online!](https://tio.run/##KypNqvz/X8XOxkapQF1ZJV5d6f//1IrE3IKcVIXikqLMvHQFA0MjYxNTM3MLy3/5BSWZ@XnF/3XzAA "Ruby – Try It Online")
[Answer]
# [Aceto](https://github.com/aceto/aceto), ~~14~~ ~~13~~ 11 bytes
```
'"drsJJp'pp
```
[Try it online!](https://tio.run/##S0xOLcn//19dKaWo2MurQL2g4P9/p9ScnPx/@QUlmfl5xf91cwA)
```
'"       push a quote character
  d       duplicate
   r       get input
    s       swap top stack items, so the input is between the two quotes
     JJ      Join top two items, 2x
       p  p    print
        'p      push literal:p
```
[Answer]
# Javascript, 20 bytes
Uses eval to make a new function from the input string.
```
a=>eval(`a=>'${a}'`)
```
[Answer]
# [Julia 0.6](http://julialang.org/), 18 bytes
```
x->"print(\"$x\")"
```
[Try it online!](https://tio.run/##yyrNyUw0@59mm5Sanpn3v0LXTqmgKDOvRCNGSaUiRklT6X9qXgpXsa1SYnFaTnaekbGRpbFLsJtjsJuLo5sSl0NxRn65QppGsSZXallijkZBYlFxqgaIr6n5HwA "Julia 0.6 – Try It Online")
[Answer]
# JavaScript Firefox, 6 bytes
```
uneval
```
[Answer]
# WinDbg, 14 bytes
```
.echo.echo $u0
```
Input is taken by setting the fixed name alias `$u0` (so that input can be either a string or number).
Running this will print:
```
.echo {value_of_$u0}
```
Which when executed prints the input.
Example:
```
$$ set input
r$.u0=testing123
$$ run code
.echo.echo $u0
$$output: .echo testing123
$$ run output
.echo testing123
$$output: testing123
```
How it works:
```
.echo            $$ print the rest of the statement
     .echo       $$ part of the string that gets printed
           $u0   $$ automatically expands to the value of the fixed name alias,
                 $$ the expanded alias is printed
                 $$ because only a-zA-Z0-9 needs to be handled, no special logic around the
                 $$ alias expansion with regard to spaces, ", or ; interfering with the
                 $$ next .echo needs to be done
```
How the output works:
```
.echo            $$ print the rest of the statement
      {string}   $$ the string that gets printed, guaranteed to be one statement because
                 $$ it can't contain ; or " and can't start with a space
```
[Answer]
# T-SQL, 28 bytes
```
SELECT'PRINT'''+s+''''FROM t
```
An input table is [allowed per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), so I simply create a `PRINT` statement with the appropriate quotation marks.
An input of `FooBarBaz109481` in the input table *t* will result in the following output:
```
PRINT'FooBarBaz109481'
```
Which will output the original string.
The original question says the string will only contain alphanumerics, so we won't have to handle any quote marks in the input itself.
[Answer]
## [JavaScript (Node.js)](https://github.com/nodejs/node), 49 bytes
```
console.log('console.log("'+process.argv[2]+'")')
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP11DHZmjpK5dUJSfnFpcrJdYlF4WbRSrra6kqa75//9/j9ScnHwdhfL8opwURQA "JavaScript (Node.js) – Try It Online")
Takes input through `argv[2]`, the first argument in TIO (May be different depending on where it is tested), and prints in the `console.log("YOUR_MESSAGE")` format. Requires a string **without** quotes (unless escaped with `\`) with available characters `A-Z`, `a-z`, and `0-9`.
### Explanation
```
console.log(           // Log the output (open the outer log statement)
  'console.log("'      // Take console.log with opening parenthesis and quote
    + process.argv[2]  // Add the command-line argument after the quote (the input)
    + '")'             // Add the closing quote and parenthesis
)                      // Close the outer log statement
```
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
cat("cat(",scan(,""),")",sep="\"")
```
[Try it online!](https://tio.run/##K/r/PzmxREMJTOgUJyfmaegoKWnqKGkCeakFtkoxQN7/lNKUzOLizNz8/wA "R – Try It Online")
Non-functional answer - longer than the functional one
[Answer]
# R, ~~5~~ ~~4~~ ~~1~~ 0 bytes
Thanks to JayCe for contributing the one-byte answer!
There are a number of short R programs that would ...
>
> take a string as input, and output a piece of code in the same
>  language that, when run, will output the initial input string
>
>
>
. Some of these are listed below, one on each row, in descending order of length:
```
identity     # 8 bytes
force        # 5 bytes
print
eval         # 4 bytes
c            # 1 byte
             # 0 bytes
```
This is inspired by NoOneIsHere's 1-byte answer in Pyth which is said to "just evaluate the input". This is exactly what `force` and `identity` do. `eval` and `c` achieve the same result in different ways. But why stop here? When you feed a string into R, it will be evaluated (to itself) and printed in quotes. A quoted string is a valid R program. That's the idea of the 0-byte answer.
Uniquely, the same program works identically in R and Python:
## R way
```
> "yo ho ho and a bottle of rum"
[1] "yo ho ho and a bottle of rum"
```
## Python way
```
>>> 'yo ho ho and a bottle of rum'
'yo ho ho and a bottle of rum'
```
[Answer]
# Excel VBA, 10 bytes
An anonymous function that outputs an anonymous function that prints the value of cell `A1`.
```
?"?"""[A1]
```
### Example I/O
Given that cell `[A1]` that is populated with `One`
```
?"?"""[A1]
?"One
One
```
[Answer]
# [Yabasic](http://www.yabasic.de), 22 bytes
An anonymous function that takes input, `S$` as a string and outputs a function that outputs `S$` to the console.
This relies on the fact that the `Input` Call will print a `?` character to the console as a prompt when no explicit prompt is provided
```
Input S$
?"\""+S$+"\""
```
[Try it online!](https://tio.run/##q0xMSizOTP7/3zOvoLREIViFy14pRklJO1hFG0T//x@SWlwCAA "Yabasic – Try It Online")
[Answer]
# [Lua](https://www.lua.org), 29 bytes
```
print('print("'.. ... ..'")')
```
[Try it online!](https://tio.run/##yylN/P@/oCgzr0RDHUIpqevpKeiBsbqSprrm////PVJzcvJ1FMLzi3JSAA "Lua – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 79 bytes
```
println(s"""object x{def main(a:Array[String])=println("${args.mkString}")}""")
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcolChUM2loJCSmqaQm5iZp5FYlF5speBYVJRYGR1cUpSZlx6raaUQmpdZomCrUP2/AChSkpOnUaykpAQzoBqh2QpVoy1MuZJKNchgvdxsiFStkmYt0ATN/7Vctf//JwKBjqEBAA "Scala – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 12 bytes
```
$_="say'$_'"
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lapOLFSXSVeXen//5KMzGIFIEpUKEktLvmXX1CSmZ9X/F@3AAA "Perl 5 – Try It Online")
[Answer]
# Rust, 26 bytes
Input needs to be enclosed in double quotes: `""`
```
|a|print!("||print!({a})")
```
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f441851309dda428841107dffa4bd34a)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 1 [byte](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ṙ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWix_unLGkOCm5GMpfsKoktbgkMy_d0MgYIgIA)
Built-in for "repr" (Thunno 2 has implicit input). Essentially this surrounds the string with double quotes. So, when you run the program a string gets pushed to the stack and gets implicitly output.
]


[Question]
      [
You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a [truthy or falsy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value, and IO can be in any [reasonable format](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
# Rules and definitions:
* For the purpose of this challenge, a "bracket" is any of these characters: `()[]{}<>`.
* A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
```
()
[]{}
```
Or if every subelement inside of it is also matched.
```
[()()()()]
{<[]>}
(()())
```
Subelements can also be nested several layers deep.
```
[(){<><>[()]}<>()]
<[{((()))}]>
```
* A string is considered "Fully matched" if and only if:
	1. Every single character is a bracket,
	2. Each pair of brackets has the correct opening and closing bracket and in the right order, and
	3. Each bracket is matched.
* You may assume the input will only contain [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
# Test IO
Here are some inputs that should return a truthy value:
```
()
[](){}<>
(((())))
({[<>]})
[{()<>()}[]]
[([]{})<{[()<()>]}()>{}]
```
And here are some outputs that should return a falsy value:
```
(               Has no closing ')'
}{              Wrong order
(<)>            Each pair contains only half of a matched element
(()()foobar)    Contains invalid characters
[({}<>)>        The last bracket should be ']' instead of '>'
(((()))         Has 4 opening brackets, but only 3 closing brackets.
```
As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~1101, 1085~~, 981 bytes
```
{(<(({}))((((()()()()()){}){}){})({}[{}]<(())>){((<{}{}>))}{}>{({}<>)(<>)}{}<(({
}))((((()()()()()){}){}){}())({}[{}]<(())>){((<{}{}>))}{}>{({}<>)({}[{}](<()>)){
{}{}(<(())>)}{}{<>{{}}<>{{}}((<()>))}{}(<>)}{}<(({}))(((((()()()()()){}){})){}{}
)({}[{}]<(())>){((<{}{}>))}{}>{<({}()<>)>()(<>)}{}<(({}))(((((()()()()()){}){})(
)){}{})({}[{}]<(())>){((<{}{}>))}{}>{<({}()<>)>()({}[{}](<()>)){{}{}(<(())>)}{}{
<>{{}}<>{{}}((<()>))}{}(<>)}{}<(({}))((((()()()){}){}()){({}[()])}{})({}[{}]<(()
)>){((<{}{}>))}{}>{<({}()()<>)>()(<>)}{}<(({}))((((((()()()()()){})){}{}())){}{}
)({}[{}]<(())>){((<{}{}>))}{}>{<({}()()<>)>()({}[{}](<()>)){{}{}(<(())>)}{}{<>{{
}}<>{{}}((<()>))}{}(<>)}{}<(({}))((((((()()()()()){}){}){}())){}{})({}[{}]<(())>
){((<{}{}>))}{}>{<({}()()()<>)>()(<>)}{}<(({}))((((((()()()()()){}){}){}())()){}
{})({}[{}]<(())>){((<{}{}>))}{}>{<({}()()()<>)>()({}[{}](<()>)){{}{}(<(())>)}{}{
<>{{}}<>{{}}((<()>))}{}(<>)}{}<{}>[()]){<>{{}}(<()>)<>{{}}(<()>)}{}}<>([]<>)({}<
(())>){((<{}{}>))}{}
```
[Try it online!](https://tio.run/##rZNBDsIgFESvM7PoDQgXaVjgwsRoXLj94ew4QDU11Uq1pYVfGCZvUnq4xdN1OF7iOWeDAyyRKBcfjZpqtxZHS0Eq0tMAZ8mSJ0tvWnWe0KPXdSeVXV5NIyxJaEWAaYNKc15TqfWYRFWyIFggsHh9YXAooDLzYI8ntrvulW@GUcbiCwb20qylfI1ZE6rsT7p71g/naQtRf97naf3N/6/McqxfcdI1wbxOdTfG0H6Vt1A5o7I7P4aYh3gH "Brain-Flak – Try It Online")
This is 980 bytes of source code, and `+1` for the `-a` flag allowing ASCII input (but decimal output)
This is an answer I've been wanting to write for a *very very* long time. At least 6 months. I waited to post this because I knew that answering this challenge would be extra hard in brain-flak. But it's worth it for one very important reason: The source code itself is a truthy input, which is the entire point of this language itself.
And as I wrote about [here](http://meta.codegolf.stackexchange.com/a/9957/31716), this question was what inspired me to write brain-flak.
>
> Shortly after I wrote Are the brackets fully matched?, it made me wonder how much information you can store with only matched brackets. One thing that stood out to me, was that even though you only have 4 "atoms" of sorts:
>
>
>
> ```
> (){}[]<>
>
> ```
>
> you really have 8 units of information to convey, since each of these bracket types can be empty, or have other brackets in between, which are fundamentally different pieces of information. So, I decided to write a language that only allowed for matched brackets, and where empty brackets convey something different than brackets with other brackets inside of them.
>
>
>
This answer took roughly two hours to write. I'll admit it's pretty poorly golfed, mostly because a lot of the code is repeated for each bracket type. But I'm mostly amazed that I was able to write an answer at all, especially given that Brain-Flak is
>
> A minimalist esolang designed to be painful to use
>
>
>
I'm going to attempt to golf it down later, but I wanted to get this out there anyway.
I have a detailed explanation, but it's about 6 thousand characters long, so I think it would not be wise to paste the entire thing into this answer. You can read through it [here](https://gist.github.com/DJMcMayhem/52453a771830a0dcd42323d39396ce54) if you want. I'll add a shorter explanation here.
The basic idea, is that we repeat the following steps for every character on the stack:
* We check each character to see if it matches any bracket. If it is an opening bracket, we push a number onto the other stack according to the following mapping:
```
( = 1
< = 2
[ = 3
{ = 4
```
* Then we check to see if it matches any closing bracket. If it does, we push the equivalent number onto the alternate stack, just like for opening brackets. *Then*, we check if the top two numbers are equal. If they are, the both get popped and the program continues as normal. If they are not, we clear both stacks (to stop the looping) and push a one onto the alternate stack. This is essentially a "break" statement.
* After checking the 8 bracket types, we push the value of this run through the loop. Since we zero out most of it, the only snippets that have any value are the conditionals when we compare against brackets. So if any bracket is matched, the whole loop has a value of 1. If none of them did, the whole loop has a value of 0. In this case, we will clear both stacks and push a 0 onto the alternate stack. Again, this is like a "break" statement.
After this main loop is running, the rest is fairly simple. We are on the (empty) main stack, and the alternate stack is empty (if the brackets were matched) or non-empty if they were not. So we run this:
```
#Toggle to the alternate stack
<>
#Push this stack-height onto main-stack
([]<>)
#Logical not
({}<(())>){((<{}{}>))}{}
```
This will push a 0 or a 1 onto the main-stack, and when the program ends it is implicitly printed.
---
* *Thanks to [@WheatWizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) for coming up with a good stack-clean "equals" and "logical not" snippet, and for regularly updating the [github wiki](https://github.com/DJMcMayhem/Brain-Flak/wiki) with useful examples.*
* *Thanks to [@ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) for writing an online [integer metagolfer](https://brain-flak.github.io/integer/) which helped immensely in writing this program*
---
*revisions*
* *Removed some push pop redundancy*
* *Changed my zero counter logic*
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~204~~ ~~196~~ 190 bytes
```
{({}<>)<>((((()()()()()){})(({}){})())({}(({})((({}){})(<()>))))())(({<({}<>[({})])>[()]{()(<{}>)}{}<>}{}()<({}<>[({})]){(<{}({}())>)}{}<>>)){(<({}{}<>[{}]{}<>)>)}{}{<>{{}}}{}}<>((){[()]<>})
```
[Try it online!](https://tio.run/##1Y5BCsMwDAS/oz3kB0IfKT64h0Bo6KHXRW9PVyIp5AmVwZI1y3qfn7m9l3Wfr@OgMT3gYVW4Dpgwoe6Apn7Zb@eGgKqg0dvlUXBAHYNycWYgi@gy3EQsWrbAqZGdllq1ijk6WEN6kJmasoKC9YNc8ff5l/kF "Brain-Flak – Try It Online")
-8 bytes thanks to Wheat Wizard. -6 bytes thanks to Jo King.
### Explanation
This program stores the character codes of all current unclosed brackets on the second stack. The bracket pairs `<>`, `[]`, and `{}` each have character codes that differ by exactly 2, so there is no need to check for them specifically. The pair `()` only differs by 1, so we check for `(` specifically, and effectively decrement that byte (actually increment every other byte) before continuing.
```
# While there are bytes left to process
{
 # Move byte to second stack
 ({}<>)<>
 # Push 40, 0, 40, 60, 91, 123: (, then null, then all four opening brackets
 ((((()()()()()){})(({}){})())({}(({})((({}){})(<()>))))())
 ((
   # For each opening bracket type:
   {
    # Evaluate as zero
    <
     # Compute difference between bracket type and input byte
     ({}<>[({})])
    >
    # Evaluate loop iteration as -1 if equal, 0 otherwise
    [()]{()(<{}>)}{}<>
   }
   # Remove the 0 that was inserted to terminate that loop
   {}
   # Add 1 to result
   ()
   # Evaluate rest of this expression as zero
   <
    # Determine whether the byte is open parenthesis
    ({}<>[({})])
    # If not:
    {
     # Add 1 to byte and break if
     (<{}({}())>)
    }{}
    # Return to main stack
    <>
   >
 # Push result twice (0 if matched an opening bracket, 1 otherwise)
 ))
 # If byte was not an opening bracket:
 {
  # Push zero to break out of if
  (<
    # Push (open bracket + 2 - byte) below that zero
    ({}{}<>[{}]{}<>)
  >)
 }{}
 # If byte was neither an opening bracket nor the appropriate closing bracket:
 {
  # Clear alternate stack and stay there to break out of main loop early
  <>{{}}
 }{}
# End of main loop
}
# If a prefix was invalid, the top of the other stack is the same nonzero value
# that made us break out in the first place. If the string was a valid prefix,
# the other stack contains every unclosed bracket.  If the string is balanced,
# there are none of these. Thus, the other stack is empty if the
# brackets are balanced, and has a nonzero value on top otherwise.
# Push 1 on other stack if empty, and 0 on current stack otherwise
<>((){[()]<>})
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 19 bytes
Input is given in *quotes*. Code:
```
"[](){}<>"2÷)"":g2Q
```
Well crap, a *lot* of bugs and unimplemented features were found. Explanation:
```
"[](){}<>"           # Push this string
          2÷         # Split into pieces of two
            )        # Wrap it into an array (which should not be needed)
             ""      # Push an empty string
               :     # Infinite replacement
```
This is actually a tricky part. What this looks like in pseudocode is:
```
input().replace(['[]', '()', '{}', '<>'], "")
```
This is covered by this part from the [05AB1E code](https://github.com/Adriandmen/05AB1E/blob/master/05AB1E.py#L1498):
```
if type(b) is list:
    temp_string = temp_string_2 = str(a)
    while True:
        for R in b:
            temp_string = temp_string.replace(R, c)
        if temp_string == temp_string_2:
            break
        else:
            temp_string_2 = temp_string
    stack.append(temp_string)
```
As you can see, this is **infinite replacement** (done until the string doesn't change anymore). So, I don't have to worry about setting the replacement into a loop, since this is already builtin. After that:
```
                g    # Take the length of the final string
                 2Q  # Check if equal with 2 (which are the quotes at the end)
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=IltdKCl7fTw-IjLDtCIiOmcyUQ&input=J1soW117fSk8e1soKTwoKT5dfSgpPnt9XSc) (slightly modified because the above version is deprecated).
[Answer]
## JavaScript (ES6), ~~52~~ 50 bytes
```
f=s=>(t=s.replace(/\(\)|\[]|{}|<>/,''))==s?!s:f(t)
```
Repeatedly remove brackets until the result is the same as the original, then return false unless the string is now empty.
Edit: Saved 2 bytes thanks to @edc65.
[Answer]
## Python, 67 bytes
```
lambda s:eval("s"+".replace('%s','')"*4%([],(),{},'<>')*len(s))==''
```
Generates and evals an expression that looks like
```
s.replace('[]','').replace('()','').replace('{}','').replace('<>','').replace('[]','').replace('()','').replace('{}','').replace('<>','')
```
and checks if the result is empty.
Sp3000 saved 8 bytes by pointing out that `[],(),{}` can be subbed in without quotes because they're Python objects, and that two parens were unneeded.
[Answer]
# Retina, 20 bytes
```
+`\(\)|\[]|{}|<>
^$
```
[Try it online](http://retina.tryitonline.net/#code=K2BcKFwpfFxbXXx7fXw8PgoKTWBeJA&input=WygpKCkoKSgpXQ)
[Answer]
## CJam, ~~25~~ ~~24~~ ~~23~~ 21 bytes
*Thanks to Sp3000 for saving 2 bytes.*
*Thanks to jimmy23013 for saving 2 bytes.*
```
q_,{()<>}a`$2/*{/s}/!
```
[Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%7B%0A%0AQ_%2C%7B()%3C%3E%7Da%60%242%2F*%7B%2Fs%7D%2F!%0A%0A%7D%26%5DoNo%7D%2F&input=()%0A%5B%5D()%7B%7D%3C%3E%0A(((())))%0A(%7B%5B%3C%3E%5D%7D)%0A%5B%7B()%3C%3E()%7D%5B%5D%5D%0A%5B(%5B%5D%7B%7D)%3C%7B%5B()%3C()%3E%5D%7D()%3E%7B%7D%5D%0A%0A(%0A%7D%7B%0A(%3C)%3E%0A(()()foobar)%0A%5B(%7B%7D%3C%3E)%3E%0A(((())))
Works essentially the same as the other answers: we repeatedly remove `()`, `[]`, `<>` and `{}` from the string and check if we end up with the empty string. To avoid having to check when we're done, we remove the pairs `N` times where `N` is the length of the string, which is always sufficient (since each iteration will remove at least two characters, unless we're done). I'm glad to see that this doesn't beat Retina. :) (Although Pyth or Jelly might...)
There's one fun golfing trick here: to get the string `()<>[]{}` we use the following:
```
{()<>}a`$
```
The, `{()<>}` is just a block (i.e. a function), which contains the other brackets as code. With `a` we wrap the block in an array. The ``` stringifies that array, which gives `"[{()<>}]"`. Finally, we sort the string with `$`, which rearranges the brackets to `()<>[]{}`.
[Answer]
# Yacc, 119 bytes
Does not use regex/replace.
```
%%input:r;r:%empty|'['r']'r|'{'r'}'r|'('r')'r|'<'r'>'r;%%yylex(){return getchar();}main(){return yyparse();}yyerror(){}
```
## Ungolfed
```
%%                              # Grammar in BNF
input:
  r;
r:
  %empty
| '['r']'r
| '{'r'}'r
| '('r')'r
| '<'r'>'r;
%%                              # Minimal parser invocation and lexer
yylex(){return getchar();}
main(){return yyparse();}
yyerror(){}
```
## Compilation
```
yacc -o bracket.c bracket.y
cc -o bracket bracket.c
```
## Usage
```
~/ % echo -n "<()[]>" | ./bracket
~/ %
~/ % echo -n "{" | ./bracket
~/ 1 %                                                                         :(
```
[Answer]
## Pyth, ~~31~~ ~~25~~ 24 bytes
Golfed down to 25 bytes thanks to FryAmTheEggMan
Removed 1 byte
```
VQ=:Q"<>|\[]|{}|\(\)"k;!
```
Try it here: [Test suite](https://pyth.herokuapp.com/?code=Vz%3D%3Az%22%3C%3E%7C%5C%5B%5D%7C%7B%7D%7C%5C%28%5C%29%22k%3B%21z&test_suite=1&test_suite_input=%28%29%0A%5B%5D%28%29%7B%7D%3C%3E%0A%28%28%28%28%29%29%29%29%0A%28%7B%5B%3C%3E%5D%7D%29%0A%5B%7B%28%29%3C%3E%28%29%7D%5B%5D%5D%0A%5B%28%5B%5D%7B%7D%29%3C%7B%5B%28%29%3C%28%29%3E%5D%7D%28%29%3E%7B%7D%5D%0A%28%0A%7D%7B%0A%28%3C%29%3E%0A%28%28%29%28%29foobar%29%0A%5B%28%7B%7D%3C%3E%29%3E%0A%28%28%28%28%29%29%29&debug=0) !
I'm still a Pyth newbie, any help is appreciated.
## Explanation
```
VQ                         For N in range(0, len(z)), with Q being the evaluated input.
                           Optimal solution would be to use range(0, len(z)/2) instead, but it add two bytes.
  =:Q"<>|\[]|{}|\(\)"k     assign Q without {}, [], <> nor () (regex replacement) to Q
                      ;    End of For loop
                       !   Logical NOT of Q's length (Q is the input, but has gone several times through y, and Q is implicit).
                           This last operation returns True if len(Q) is 0 (which means all brackets were matched), False otherwise
```
BTW, congrats to the other Pyth answer (which is currently 20 bytes)
[Answer]
# Pyth, 20 bytes
```
!uuscNTc"[](){}<>"2G
```
Try it online: [Test Suite](http://pyth.herokuapp.com/?code=!uuscNTc%22[]%28%29%7B%7D%3C%3E%222G&input=%22%28[%29]%22&test_suite=1&test_suite_input=%22%28%29%22%0A%22[]%28%29%7B%7D%3C%3E%22%0A%22%28%28%28%28%29%29%29%29%22%0A%22%28%7B[%3C%3E]%7D%29%22%0A%22[%7B%28%29%3C%3E%28%29%7D[]]%22%0A%22[%28[]%7B%7D%29%3C%7B[%28%29%3C%28%29%3E]%7D%28%29%3E%7B%7D]%22%0A%22%28%22%0A%22%7D%7B%22%0A%22%28%3C%29%3E%22%0A%22%28%28%29%28%29foobar%29%22%0A%22[%28%7B%7D%3C%3E%29%3E%22%0A%22%28%28%28%28%29%29%29%22&debug=0)
Repeatedly removes occurrences of `[]`, `()`, `<>` and `{}` by splitting and re-merging. Checks if the resulting string is empty or not.
[Answer]
# Javascript ES6, 54 bytes
```
f=_=>_.match(x=/\(\)|\[]|{}|<>/)?f(_.replace(x,'')):!_
```
Uses a recursive replace implementation. Simple enough.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 204 bytes
```
(()){{}{({}<>)<>}<>({<(<(({})<>)>)(((((((([(())()()()]){}){}){}())(()))(((())()){}()){})){})(({<(({}<>{}[()]))>(){[()](<{}>)}{}<>}{}))<>{}<>{{}({}[({})]<>({})){(<>)(<>)}{}{}(<>)}{}>{}<>}<>)}{}((){<>[()]})
```
[Try it online!](https://tio.run/##3U9BDsMgDPuOfegPonyk6oEdKlWbdtg1yts7G/aKAUbBdgw8PuN6b@drPO8bIKu6UB3JSO2oQECEjkziN3ZbMedBiXOZEqbJ6qIkGXDSDK7e3cUEyxWiOtmW2mY7BDXbKebwM5wCvcGQTeoqprlXrWsr0pnNP/vNNr4 "Brain-Flak – Try It Online")
Not quite as short as [Nitroden's answer](https://codegolf.stackexchange.com/a/142224/76162), but uses a very different approach. This one runs through the input repeatedly, removing neighbouring matching pairs of brackets each time until there are none left. At that point if there is anything left on the stack, then the string was not fully matched.
### Explanation:
```
(())  Push 1 to simulate the check at the start of the loop
{  While check
	{}           Pop check
	{({}<>)<>}<> Reverse input
	({           Loop over input
		< Don't push the values of these calculations
		(<(({})<>)>)  Create a copy of the top of the input and push to the other stack
		(((((
		((([(())()()()]){}){}){}())
		(()))
		(((())()){}()){})
		){})          Push the differences in values of the end brackets
		(({<(({}<>{}[()]))>(){[()](<{}>)}{}<>}{}))  If the copy is the same as any of these, push the difference between the other bracket twice
		<>{}<>  Pop copy
		{  If this character is a start bracket
			{}({}[({})]<>({}))  Check if the next character is the end bracket
			{(<>)(<>)}{}          If not, push a 0 to each stack as buffer
			{}       Pop the top of the input stack, either the start bracket if they matched or the buffer 0
			(<>)     Push 0 to other stack to end check
		}{}>
		{}   Pop the top of the other stack
		         If the character was not an end bracket, pop the copy of check, which is 0
		         If it was, but didn't match the next character, pop the buffer 0
		         If the brackets matched, pop the end bracket and add it to the loop total
	<>}	Repeat with the rest of the input
	<>)	Push the loop total
		If any brackets were matched, the loop total is non zero
}{}
((){<>[()]}) If there is anything left on the stack, push 0 to the other stack, otherwise push 1
```
[Answer]
# Regex (PCRE flavor), ~~41~~ 37 bytes
```
^((<(?1)>|{(?1)}|\[(?1)]|\((?1)\))*)$
```
Just a standard solution with recursive regex.
*Thanks jimmy23013 for shaving off 4 bytes*
[Answer]
## Brainfuck, 132 bytes
```
+>,[[<->>+>[-]<<-]<[>+>[<+<+>>>+<-]+++++[>--------<-]>[<<+>++++[>-----<-]>[<++++
+[>------<-]>-[<++++[>--------<-]>[,>]]]]<],]<<[>]>.
```
Formatted:
```
+>,
[
  [<-> >+>[-]<<-]
  <
  [
    not matching closing bracket
    >+>[<+<+>> >+<-]
    +++++[>--------<-]
    >
    [
      not open paren
      <<+>
      ++++[>-----<-]>
      [
        not open angle bracket
        <+++++[>------<-]>-
        [
          not open square bracket
          <++++[>--------<-]>
          [
            not open brace
            ,>
          ]
        ]
      ]
    ]
    <
  ]
  ,
]
<<[>]
>.
```
Expects input without a trailing newline. Prints `\x00` for false and `\x01` for true.
[Try it online.](http://brainfuck.tryitonline.net/#code=Kz4sW1s8LT4-KzwtXTxbPis-PlstXTxbPCs8Kz4-Pis8LV0rKysrK1s-LS0tLS0tLS08LV0-Wzw8Kz4rKysrWz4tLS0tLTwtXT5bPCsrKysrWz4tLS0tLS08LV0-LVs8KysrK1s-LS0tLS0tLS08LV0-Wyw-XV1dXTxdLF08PFs-XT4u&input=WyhbXXt9KTx7WygpPCgpPl19KCk-e31d)
Approach: Maintain a stack starting with `\x01`, and push the corresponding closing bracket whenever an opening bracket is encountered. Before checking whether the current character is an opening bracket, first check whether it's equal to the closing bracket at the top of the stack, and if so pop it. If it's neither the proper closing bracket nor an opening bracket, consume the rest of the input while moving the pointer to the right. At the end, check whether the pointer is next to the initial `\x01`.
[Answer]
# Perl, ~~34~~ 33 bytes
Includes +2 for `-lp`
Run with input on STDIN:
```
./brackets.pl <<< "{<>()}"
```
`brackets.pl`:
```
#!/usr/bin/perl -lp
s/\(\)|\[]|<>|{}//&&redo;$_=!$_
```
Finds the first bracket pair without anything between them and removes it as long as there are any. Then checks if the final string is empty.
[Answer]
# Java 7, ~~156~~ 151 bytes
```
class A{public static void main(String[]a){for(int i=0;i<-1>>>1;++i,a[0]=a[0].replaceAll("<>|\\[]|\\(\\)|\\{}",""));System.out.print(a[0].isEmpty());}}
```
I'm not expecting this to win any awards but I didn't see a Java answer yet. Additionally, I like to lurk around PPCG and I would enjoy being able to vote/comment on other answers.
Input is given as program parameters. This follows the same format as many other answers here in that it preforms a regex replacement in a loop. Originally I had it loop N times where N is the length of the original string but looping to `Integer.MAX_VALUE` is shorter :]. This should be ok because `Integer.MAX_VALUE` is the maximum length of a `String` in Java so there's an implicit assumption that the length of input is something that is handle-able by Java. The runtime is pretty bad (took about 20 minutes on my lappytop) on account of the loop but I didn't see any restriction on that.
[Answer]
# [Haskell](https://www.haskell.org/), 151 bytes
```
infix 1#
'(':x#y=x#')':y
'<':x#y=x#'>':y
'[':x#y=x#']':y
'{':x#y=x#'}':y
')':x#')':y=x#y
'>':x#'>':y=x#y
']':x#']':y=x#y
'}':x#'}':y=x#y
""#""=1
_#_=0
```
[Try it online!](https://tio.run/##PcuxCsMgFIXh3acoWlDHrkEd@wTd5BIcLJXaUJIWDHKf3ZoLdTnwHfgfYXvGnFtLyz2V00UwqeRUxG6LkFpOO5Nm2JH9MJDrMJL1YWr71@3IbhjIMIxk/Jtzwbm9rd/IZjHba8hbZO0V0mLfa1o@Z@6Vh4raVK@0UdoB9qkIR9h@ "Haskell – Try It Online")
[Answer]
## [Grime](https://github.com/iatorm/grime/tree/v0.1) v0.1, 34 bytes
```
M=\(M\)|\[M\]|\{M\}|\<M\>|MM|_
e`M
```
Prints `1` for a match and `0` for no match.
[Try it online!](http://grime.tryitonline.net/#code=TT1cKE1cKXxcW01cXXxce01cfXxcPE1cPnxNTXxfCmVgTQ&input=WyhbXXt9KTx7WygpPCgpPl19KCk-e31d)
## Explanation
Grime is my 2D pattern-matching language designed for [this challenge](https://codegolf.stackexchange.com/questions/47311/language-design-2-d-pattern-matching); it can also be used to match 1D strings.
This is my first answer with it.
I did modify Grime today, but only to change the character of one syntax element (``` instead of `,`), so it doesn't affect my score.
```
M=                         Define pattern called M that matches:
\(M\)|\[M\]|\{M\}|\<M\>      a smaller M inside matched brackets,
|MM                          or two smaller Ms concatenated,
|_                           or the empty pattern.
e`M                        Match the entire input against M.
```
[Answer]
# Reng v.3.3, 137 bytes, noncompeting
[Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)
```
aií0#zl2,q!~1ø
:"]"eq!v:"}"eq!v:">"eq!v:")"eq!v)1z+#z
ve¤[2-2<       <       <     +1<
>]?v$$$zÀ0#z >ðq!vlqv¤l2%[1Ø
   \$2+)1z+#z/   ~n1/
```
There's a bit more golfing to be done, but at least it works. I added a command `ð` to keep track of stacks after this challenge in order for this to be remotely possible/easily. I'll explain this in a bit, but it generally keeps track of all strings iterated over and looks for repeats; if there is a repeat, then the string is irreducible. Otherwise, the string will be reduced to the empty string/stack, and will output `1`. Otherwise, no output will be produced.
[Answer]
## PowerShell v2+, ~~63~~ 62 bytes
```
param($a)for(;$a-ne$b){$a=($b=$a)-replace"\[\]|\(\)|<>|{}"}!$a
```
Can't quite catch JavaScript, but is currently edging out the other non-esolangs.
Similar approach as other answers: a simple loop that continues so long as we can remove one of `[]`, `()`, or `<>` (with several extraneous characters because we need to escape the regex specials). We use `$b` as a helper along the way to remember what our previous loop's `$a` was set as. An uninitialized variable is `$null`, so the first time the loop is encountered, `$a` is obviously not equal to `$null`.
At the end of the loop, `$a` is either empty or not, and the Boolean-not of that string is either `True` or `False`.
### Example
```
PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({})]"
True
PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({])}"
False
```
[Answer]
# C, ~~121~~ ~~122~~ 114 bytes
Shaved of 8 bytes thanks to @xsot!
```
a[99],i,k;main(c){for(;read(0,&c,!k);c%7&2?k|=a[i--]^c/9:(a[++i]=c/9))k|=!strchr("()[]{}<>",c);putchar(48+!k*!i);}
```
Uses a stack.
[Answer]
### Python 2.7, 96 bytes
```
def r(s):i=max(map(s.find,['()','[]','{}','<>']));return not len(s)if i<0 else r(s[:i]+s[i+2:])
```
[Answer]
# Julia, 51 bytes
```
~z=z==(n=replace(z,r"\(\)|\[]|{}|<>",""))?z=="":~n
```
The least insane of several options. Unsurprisingly, leveraging the power of regex is the shortest path to string matching, but this really only applies if the pattern to match is regular. Trying to do PCRE recursive patterns ends up ballooning the size of the code, either by seeing if the whole string is the match or by anchoring the ends and then creating a construct to specify the inner body for regex recursion. Neither of which are pretty or conducive to code golf.
## Explanation:
```
~z=                            # Define ~z to be the following:
    z==(                       # If z is equal to
        n=replace(z,           # z with the replacement of
            r"\(\)|\[]|{}|<>", # adjacent matching brackets ((),[],{}, or <>)
            ""                 # with empty strings
        )                      # (which is assigned to n)
    )?z==""                    # whether z is an empty string
    :~n                        # else ~ applied to the substituted string
```
The function repeatedly removes adjacent pairs of parentheses from its only argument, and returns true if it can derive an empty string this way.
[Answer]
# R, 298
```
function(.){s=strsplit;u=paste0;.=s(.,"")[[1]];p=s("><)(}{][","")[[1]];.[!.%in%p]="§";for(i in 1:4*2){.[.==p[i]]=sprintf("S('%s',{",p[i]);.[.==p[i-1]]=sprintf("},'%s');",p[i])};S=function(H,B,T)if(H!=T)stop();r=try(eval(parse(,,u(.,collapse=""))),1);if(inherits(r,"try-error"))FALSE else TRUE}
```
The approach here is to convert the sequence into R code, and then try to parse and evaluate it. If that gives an error, then return `FALSE`.
But there is a minor problem ... R's rules for brackets are different, so `<` and `>` are not brackets at all, and the other types have rules of their own. This is solved by a revolutionary approach -- a squeaking function, whose only function is to signal an error if its head and tail squeak in different ways.
For example, `[]` is transformed into `S('[', {}, ']')`, where S is defined as ...
```
S=function(H,B,T)if(H!=T)stop()
```
Because the head squeak and tail squeak match, no error is thrown.
A few other examples (the left part is a sequence of brackets and right part is its transformation into valid R code that can be evaluated):
```
[}     -->  S('[', {}, '}')     # squeaks an error
[()]   -->  S('[', {S('(',{},'(')}, "[")
({[]}) -->  S('(',{S('{',{S('[',{},'[');},'{');},'(');
```
Some other sequences of brackets will result in parse errors:
```
[[)    -->   S('[',{S('[',{},'(');
```
So the remaining part just catches the errors and returns FALSE if there are any, and TRUE if there are none.
The human-readble code:
```
 sqk <- function(.){
   s=strsplit;u=paste0
   .=s(.,"")[[1]]            # break the argument up into 1-character pieces
   p=s("><)(}{][","")[[1]]   # vector of brackets
   .[!.%in%p]="§"            # replace anything besides brackets by § (--> error)
   for(i in 1:4*2){
     .[.==p[i]]=sprintf("S('%s',{",p[i])    # '<' -->   S('<',{     ... etc
     .[.==p[i-1]]=sprintf("},'%s');",p[i])  # '>' -->   },'<');     ... etc
   }
   S=function(H,B,T)if(H!=T)stop()          # define the working horse
   r=try(eval(parse(,,u(.,collapse=""))),1) # evaluate the sequence
   if(inherits(r,"try-error"))FALSE else TRUE   # any errors?
   }
```
Applying it on sample cases:
```
truthy<-readLines(textConnection("()
[](){}<>
(((())))
({[<>]})
[{()<>()}[]]
[([]{})<{[()<()>]}()>{}]"))
falsy<-readLines(textConnection("(
}
(<2)>
(()()foobar)
[({}<>)>
(((()))"))
> sapply(truthy,sqk)
                      ()                 [](){}<>                 (((())))
                    TRUE                     TRUE                     TRUE
                ({[<>]})             [{()<>()}[]] [([]{})<{[()<()>]}()>{}]
                    TRUE                     TRUE                     TRUE
> sapply(falsy,sqk)
           (            }        (<2)> (()()foobar)     [({}<>)>      (((()))
       FALSE        FALSE        FALSE        FALSE        FALSE        FALSE
```
[Answer]
# Lua (92 bytes)
The older Lua answer is everything but golfing code. There's my proposal instead:
```
function x(s)m=""return s:gsub("%b<>",m):gsub("%b[]",m):gsub("%b{}",m):gsub("%b()",m)==m end
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~11~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é:råvm∟&1Γ
```
[Run and debug it](https://staxlang.xyz/#p=823a7286766d1c2631e2&i=%28%29%0A%5B%5D%28%29%7B%7D%3C%3E%0A%28%28%28%28%29%29%29%29%0A%28%7B%5B%3C%3E%5D%7D%29%0A%5B%7B%28%29%3C%3E%28%29%7D%5B%5D%5D%0A%5B%28%5B%5D%7B%7D%29%3C%7B%5B%28%29%3C%28%29%3E%5D%7D%28%29%3E%7B%7D%5D%0A%28%0A%7D%7B%0A%28%3C%29%3E%0A%28%28%29%28%29foobar%29%0A%5B%28%7B%7D%3C%3E%29%3E%0A%28%28%28%28%29%29%29&a=1&m=2)
Got lucky, as stax has a literal constant in it with matched pairs of brackets.
[Answer]
# Curry, ~~64~~ 56 bytes
*Tested to work in both [PAKCS](https://www.informatik.uni-kiel.de/%7Epakcs/) and [KiCS2](https://www-ps.informatik.uni-kiel.de/kics2/)*
```
f(x:a++y:b)|elem[x,y]["{}","<>","[]","()"]=f a*f b
f""=1
```
[Try it on Smap!](https://smap.informatik.uni-kiel.de/smap.cgi?browser/80)
[Try it online!](https://tio.run/##HcixCoMwEADQ3a84jg5JtYWuIcneSfeQIdocSFUkVjCk@fZUurzhDXsI8ba697CVQuwQrq6j6PnXT342RxOtwZSxQalPjD1hHK0icFeCviJE9SizGxcQArrgp/3l788WGK/@q2AN4/KBCxAgM9akLLWVmqXMOZYf)
This returns `1` if string is balanced and nothing otherwise.
## Explanation
Our definition of `f` then matches the empty string as balanced for a base case:
```
f""=1
```
Then we have the main logic:
```
f(x:a++y:b)|[x,y]=:=anyOf["{}","<>","[]","()"]=f a*f b
```
Here `*` is used like a logical and. Since the only value we can get back is `1`, this always gives back `1` when it finds results. But when it doesn't this doesn't give any result.
With that this pattern matches strings with a pair of matching brackets so that they divide the input into two balanced strings.
[Answer]
# C, 258 bytes
```
#define E else if(a==
#define D(v) {if (b[--p]!=v)z=1;}
#define F b[p++]=
main(a, v) char* v[]; {char b[99],p=0,z=0;for(;*v[1];v[1]++) {a=*v[1];if(a=='(')F 0;E '[')F 1;E '{')F 2;E '<')F 3;E '>')D(3)E '}')D(2)E ']')D(1)E ')')D(0)else z=1;}puts(z|p?"0":"1");}
```
## Degolfed, macro-substituted, commented
```
int main(int a, char* v[]) {
//           ^ this variable is used as a general purpose int variable and not as its intended purpose (argc)
    char b[99], // create a 99 byte array for storing bracket types
        p = 0, // pointer within the array
        z = 0; // error flag
    // loop through every byte of input (argv[1])
    for(;*v[1];v[1]++) {
        a=*v[1];// a is the current byte
        if(a=='(') b[p++] = 0; // record bracket type
        else if(a== '[') b[p++] = 1;
        else if(a== '{') b[p++] = 2;
        else if(a== '<') b[p++] = 3;
        else if(a== '>') {
            if (b[--p] != 3) z = 1; // error: bracket type mismatch
        } else if(a== '}') {
            if (b[--p] != 2) z = 1;
        } else if(a== ']') {
            if (b[--p] != 1) z = 1;
        }else if(a== ')') {
            if (b[--p] != 0)z = 1;
        }else z = 1; // error: invalid character
    }
    // if either z or p is not 0 print a '0', otherwise print a '1'
    // if p is not zero that means not all brackets were closed
    // if z is not zero that indicates an erro
    puts(z|p ? "0":"1");
}
```
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~100~~ ~~89~~ 86 bytes
-11 bytes: Use `any` instead of `firstOrNull`
-3 bytes: Use `chunked` instead of `split` (thanks to @leo848)
```
fun f(s:String):Boolean="()<>[]{}".chunked(2).any{it in s&&f(s.replace(it,""))}||s==""
```
[Try it online!](https://tio.run/##bVG7bsMwDNz9FQIRBCTQeOhoyB76Cx0VDWpqt0JcybDlIWD07a4cd6jVchDA4x0fp6sPvXVLNzvxZaxDElyIFMNoXUAA@p0h7XOlkTjKJmOloBQZyko2OuYdGEk2SFFpnVVQaY4kWSUGUpKmh@PK2rXdqyJnUyX92Y6QOu/fzJjvgust9P81CYxFsdq04dYNc6jEa0jZB4l6g3uHcIbDo3gGcWrEgbuNSxHoYXOHU/Ujq16871vjalhdWO@F8vI5u2v7js9UGndjG4R1Yjoek6wc26E3lxZteEo/Q/F@n@oaYFm@AQ "Kotlin – Try It Online")
[Answer]
# Python 2, 80 bytes
```
def m(s,i=0):exec's=s.replace("[({<])}>"[i%4::4],"");i+=1;'*4*len(s);return"">=s
```
]


[Question]
      [
I have a simple challenge for you this time. Given an array of positive integers **A** (or the equivalent in your language), replace each entry **Ai** with the sum of the next **Ai** elements of **A**, cycling back from the beginning if there are not enough items.
As usual, you can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and in any reasonable format, while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. You may optionally take the size of **A** as input too. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins.
# Examples / Test Cases
Given `[1,3,4,5]`, your code should output `[3,10,13,14]`, because `1` is replaced by `3`, `3` is replaced by `4+5+1=10` (notice how it wrapped back from the start), `4` by `5+1+3+4=13` and `5` by `1+3+4+5+1=14`.
Given `[3,2,1,9]`, your program should produce `[12,10,9,33]`, because we substitute `3` with `2+1+9=12`, `2` with `1+9=10`, `1` with `9` and `9` with `3+2+1+9+3+2+1+9+3=33` (notice how we wrapped back from the start more than once).
Some more test cases for you to choose from:
```
[4,3,2,1]                       -> [10,7,5,4]
[3,2,1,9]                       -> [12,10,9,33]
[1,3,4,5]                       -> [3,10,13,14]
[4,4,3,2,2]                     -> [11,11,8,6,8]
[3,5,3,2,1]                     -> [10,14,6,4,3]
[3,2,4,3,2,1,1]                 -> [9,7,7,4,2,1,3]
[7,8,6,5,4,3,2,1,5]             -> [29,33,20,15,11,8,6,5,30]
[28,2,4,2,3,2,3,4,5,3]          -> [137,6,10,5,9,7,12,38,39,34]
[1,2,3,4,5,4,3,2,1,2,3,4,3,2,1] -> [2,7,13,14,12,8,5,3,2,7,9,7,4,2,1]
```

[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 bytes
```
"G@:X@+)s
```
[Try it online!](https://tio.run/##y00syfn/X8ndwSrCQVuz@P//aEMdYx0THdNYAA "MATL – Try It Online")
```
	% implicit input
"	% for loop, iterate over the input array
G	% push input x
@	% push for loop index, x[i]
:	% range, push [1,...,x[i]]
X@	% push for loop index, i
+	% sum, so stack holds [i+1,...,i+x[i]]
)	% index, modularly, so gets the cyclic successors
s	% sum cyclic successors, leaving the sum on the stack
	% implicit end of for loop
	% implicit output of stack
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ṙJṁS¥"
```
[Try it online!](https://tio.run/##y0rNyan8///hzpleD3c2Bh9aqvT/cPvRSQ93zvj/P9pQx0jHWMdExxSIjYFsGB/MjgUA "Jelly – Try It Online")
[Answer]
# [Python](https://docs.python.org), 55 bytes
```
lambda a:[sum((-~v*a)[i:i+v])for i,v in enumerate(a,1)]
```
**[Try it online!](https://tio.run/##VY7BDoIwEETvfsXe2upyoKAiif5I4VBjiU2kECgkXvx1bBc52Ev3zcxOtn/7Z@eypblWy0u394cGXapxajlPPvNeC2VLe5hr0XQDWJzBOjBuas2gveEaU1Ev0fJm9NHjKscMJaY1KvrxEqY0aDkew5Tj6kvyj3/Z3ybxGQs8BX/T4q4sKCRJokLMqHyjLbzyWi3KHYTXD9Z5zgAY0q0IrHLJLVDDIwsSmFi@ "Python 3 – Try It Online")**
[Answer]
# J, 33 bytes
```
[:({.+/@{.}.)"1 i.@#|."{($~>./*#)
```
## ungolfed
```
[: ({. +/@{. }.)"1 i.@# |."0 _ ($~ (>./ * #))
```
## explanation
[![enter image description here](https://i.stack.imgur.com/5lY8N.png)](https://i.stack.imgur.com/5lY8N.png)
[Try it online!](https://tio.run/##fZDNasJAFIX3eYpDLJjROmb@nElAEYSuunLrUirVjQ@Qtq@e3jv5MYomJAOB@c797rnUqZyesC4xxTtylPQtJHb7z4/6UGaVnC@3lfyVIlU4y@3kR6ZV9va3kcvZRNQiSb6O31dkJ1gYaCiB58@ihMrh4WB7JAIoxhDNVAFjekgRZuFGIMOMotMO5Bo9LV5OUvwGrBAGfm5sqWYlZYmh9Lut2jKekUQV1IOnO3zjxvk43fXsw4rEaS4Cmma6TpYE8z5Bhzhax4DYEoy49zWeILJ2UYLqNQGGYu2g347tRJr/tgjWYJLrZT60HfkYGHdK6n8 "J – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~86~~ 85 bytes
* Saved a byte thanks to [Jakob](https://codegolf.stackexchange.com/users/44945/jakob).
```
C(y,c,l,i,k)int*y;{for(l=~0;++l<c;printf("%d,",k))for(k=i=0;i++<y[l];k+=y[(l+i)%c]);}
```
[Try it online!](https://tio.run/##jZLbaoQwEIav26dYhIWkzkKOqxLtzT6G60WxbBGtLUtvROyr20k83GwoERVNJt8/88/Up4@6nucLGaCGDhpoadP/vAxmvH3dSVf8MhPHXV6b7zuu30h0fIcIg6jdboumYKaJ43wou8q0cTGUpIsbeqwraqb5863pCR2fn7bDB7zKiJoLIbhQVnTkE3C6w6trn59eDyUH/Lr2GPnfWQUSBCBBeQgMEtCggkAOA5kfhFsMMpAyCMUxJwXai5KWxPGtAstbChQTaE9eHPBO4YxPWI16s0t77cKszk4x1LHVfktMHokZ@p9gjI0IYyauGr1z0cTskStcKwTmqzcDsDAWpCBSl7ZwAq5PIHH@mMcPmSAYXdFgC8EhkClIlFaBU7Dxt2KW/7UB3NMBYWXcbKBYujYrceqLibvuNP8B "C (gcc) – Try It Online")
[Answer]
## Haskell, ~~50~~ ~~47~~ 44 bytes
```
zipWith((sum.).take)<*>scanr(:)[].tail.cycle
```
[Try it online!](https://tio.run/##dY7NDoIwEITvPsUePIBZSSigaMTX8IA9NJWfhoINxYM@vJW0chDicWd2vpma6aaQ0pQZXM1LqIsYas/Tjzbwg4E1hX/anDVnXe8d/ZyOkpABf3JZmJaJDjK43VcAqhfdAGsoIY8xQoIh/VWthoeZGo6/MSZ0TnAMsmAkf9nf1oW3xxR3Y27y510ktWFibTsGo8XIyZkg7nZTzJuXklXabLlSHw "Haskell – Try It Online")
```
                    -- <*> in function context is Haskell's S combinator, i.e.
                    --     (zipWith ... <*> scanr ...) arg
                    -- resovles to
                    --     zipWith ... arg (scanr ... arg)
zipWith             -- so we zip
                    --   the input list and
 scanr(:)[]         --   the tails (tails of [1,2,3] are [[1,2,3],[2,3],[3],[]])
      tail          --   of the tail of
          cycle     --   and infinite cycle of the input list
                    -- with the function
 (sum.).take        --   take that many elements given by the element
                    --   of the input list from the list given by the inits
                    --   and sum it
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes
```
εL¾+èO¼
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3FafQ/u0D6/wP7Tn//9oIwsdIx0TIDYGYxMdUx3jWAA "05AB1E – Try It Online")
**Explanation**
```
ε        # apply to each element x of the input
 L       # push range [1 ... x]
  ¾+     # add counter to each (initially 0)
    è    # cyclically index into input with each
     O   # sum
      ¼  # increment counter
```
[Answer]
# [K4](http://kx.com/download/) / [K (oK)](https://github.com/JohnEarnest/ok), ~~20~~ 19 bytes
**Solution:**
```
+/'x#'1_(1+2##x)#x:
```
[Try it online!](https://tio.run/##y9bNz/7/X1tfvUJZ3TBew1DbSFm5QlO5wspQwVjBRMH0/38A "K (oK) – Try It Online")
**Examples:**
```
q)k)+/'x#'1_(1+2##x)#x:1 3 4 5
3 10 13 14
q)k)+/'x#'1_(1+2##x)#x:4 3 2 1
10 7 5 4
q)k)+/'x#'1_(1+2##x)#x:3 2 4 3 2 1 1
9 7 7 4 2 1 3
q)k)+/'x#'1_(1+2##x)#x:1 2 3 4 5 4 3 2 1 2 3 4 3 2 1
2 7 13 14 12 8 5 3 2 7 9 7 4 2 1
```
**Explanation:**
Reshape input, drop first, take x length of each, sum up.
```
+/'x#'1_(1+2##x)#x: / the solution
                 x: / store input as x
                #   / reshape
        (      )    / do this together
             #x     / count x
           2#       / duplicate (2-take)
         1+         / add 1
      1_            / 1 drop (_), remove first element
   x#'              / x take each-both
+/'                 / sum (+/) each
```
[Answer]
# [R](https://www.r-project.org/), ~~62~~ 58 bytes
```
function(a,l)diag(diffinv(matrix(a,max(a)*l+1,l))[a+2,])-a
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRJ0czJTMxXSMlMy0tM69MIzexpCizAiiemwgkNbVytA2BSjSjE7WNdGI1dRP/p2kkaxjrGOkY6lhq6pho/gcA "R – Try It Online")
An alternative to the [other R solution](https://codegolf.stackexchange.com/a/166945/67312). In the comments [JayCe made a mention of `cumsum`](https://codegolf.stackexchange.com/questions/166920/replace-me-by-the-sum-of-my-cyclic-successors/166929#comment403701_166945) which triggered something in my brain to use `diffinv` and matrix recycling instead of `rep`.
### Explanation:
Given input array `a`, let `M=max(a)` and `l=length(a)`.
Observe that `M+l` is the maximum possible index we'd need to access, and that `M+l<=M*l+1`, since if `M,l>1`,`M+l<=M*l` (with equality only when `M=l=2`) and if `l==1` or `M==1`, then `M+l==M*l+1`.
By way of example, let `a=c(4,3,2,1)`. Then `M=l=4`.
We construct the `M*l+1 x l` matrix in R by `matrix(a,max(a)*l+1,l)`. Because R recycles `a` in column-major order, we end up with a matrix repeating the elements of `a` as such:
```
      [,1] [,2] [,3] [,4]
 [1,]    4    3    2    1
 [2,]    3    2    1    4
 [3,]    2    1    4    3
 [4,]    1    4    3    2
 [5,]    4    3    2    1
 [6,]    3    2    1    4
 [7,]    2    1    4    3
 [8,]    1    4    3    2
 [9,]    4    3    2    1
[10,]    3    2    1    4
[11,]    2    1    4    3
[12,]    1    4    3    2
[13,]    4    3    2    1
[14,]    3    2    1    4
[15,]    2    1    4    3
[16,]    1    4    3    2
[17,]    4    3    2    1
```
Each column is the cyclic successors of each element of `a`, with `a` across the first row; this is due to the way that R recycles its arguments in a matrix.
Next, we take the inverse "derivative" with `diffinv`, essentially the cumulative sum of each column with an additional `0` as the first row, generating the matrix
```
      [,1] [,2] [,3] [,4]
 [1,]    0    0    0    0
 [2,]    4    3    2    1
 [3,]    7    5    3    5
 [4,]    9    6    7    8
 [5,]   10   10   10   10
 [6,]   14   13   12   11
 [7,]   17   15   13   15
 [8,]   19   16   17   18
 [9,]   20   20   20   20
[10,]   24   23   22   21
[11,]   27   25   23   25
[12,]   29   26   27   28
[13,]   30   30   30   30
[14,]   34   33   32   31
[15,]   37   35   33   35
[16,]   39   36   37   38
[17,]   40   40   40   40
[18,]   44   43   42   41
```
In the first column, entry `6=4+2` is equal to `14=4 + (3+2+1+4)`, which is the cyclic successor sum (CSS) plus a leading `4`. Similarly, in the second column, entry `5=3+2` is equal to `10=3 + (4+1+2)`, and so forth.
So in column `i`, the `a[i]+2`nd entry is equal to `CSS(i)+a[i]`. Hence, we take rows indexed by `a+2`, yielding a square matrix:
```
     [,1] [,2] [,3] [,4]
[1,]   14   13   12   11
[2,]   10   10   10   10
[3,]    9    6    7    8
[4,]    7    5    3    5
```
The entries along the diagonal are equal to the cyclic successor sums plus `a`, so we extract the diagonal and subtract `a`, returning the result as the cyclic successor sums.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
R+"Jị⁸§
```
**[Try it online!](https://tio.run/##y0rNyan8/z9IW8nr4e7uR407Di3///9/tKGOsY6JjmksAA "Jelly – Try It Online")**
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 26 bytes
```
{Sum=>_[(_2+1:_)%#_]}#Iota
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@786uDTX1i4@WiPeSNvQKl5TVTk@tlbZM78k8b9fampKcbRKQUFyeixXQFFmXklIanGJc2JxanF0mo5CNJeCgoKJurG6kbqhDogNZqlbgtmGQHETdVMdiBqIKiOoKlM0PVAzoCLm6hbqZkA1MFGIGUYWYIVGYEGw0erGUItgfJgGCB/M5oqN/Q8A "Attache – Try It Online")
## Explanation
This is a fork of two functions:
* `{Sum=>_[(_2+1:_)%#_]}`
* `Iota`
What this means is, the right tine `Iota` is applied to the argument `x` and is passed as the second argument to the center tine (the first function). So this becomes, for input `x`:
```
{Sum=>_[(_2+1:_)%#_]}[x, Iota[x]]
```
Replacing those in for `_` and `_2`:
```
Sum => x[(Iota[x] + 1:x) % #x]
```
`Iota[x]` returns an array of the indices of `x`. It's equivalent to `0...#x`. `#x` is a short way of saying the size of `x`, or `Size[x]`. In essence, this function is mapping the `Sum` function over the second expression:
```
x[(Iota[x] + 1:x) % #x]
```
The outer `x[...]` bit means that `...` will generate a series of indices to be selected from `x`. The most important part of generating the indices is this:
```
Iota[x] + 1:x
```
This expression uses a bit of vectorization. To visualize this, let's suppose the input is `x := [1, 3, 4, 5]`. Then, this expression is equivalent to:
```
Iota[[1, 3, 4, 5]] + 1:[1, 3, 4, 5]
[0, 1, 2, 3] + [1:1, 1:3, 1:4, 1:5]
[0, 1, 2, 3] + [[1], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
[0 + [1], 1 + [1, 2, 3], 2 + [1, 2, 3, 4], 3 + [1, 2, 3, 4, 5]]
[[0 + 1], [1 + 1, 1 + 2, 1 + 3], [2 + 1, 2 + 2, 2 + 3, 2 + 4], [3 + 1, 3 + 2, 3 + 3, 3 + 4, 3 + 5]]
[[1], [2, 3, 4], [3, 4, 5, 6], [4, 5, 6, 7, 8]]
```
This is a list of indices which represent the indices next `N` elements in `x` mod `#x`. To make them safe for retrieval, we take this array mod `#x`:
```
(Iota[x] + 1:x) % #x
```
This gives us the proper indices, which are then obtained from `x` and each array is summed, giving the proper results.
## Other attempts
**36 bytes:** `{Sum@_&Get=>((_2+1.._2+_)%#_)}#Iota` - I forgot `x[...]` fully vectorizes, so that becomes:
**30 bytes:** `{Sum=>_[(_2+1.._2+_)%#_]}#Iota` - but then I realized the `_2+` in the inner range could be factored out, which means we could save parentheses by using `:` instead of `..`, giving us the current version.
[Answer]
# [R](https://www.r-project.org/), ~~89~~ 64 bytes
```
j=rep(x<-scan(),max(x));Map(function(u,v)sum(j[v+1:u]),x,seq(x))
```
[Try it online!](https://tio.run/##K/r/P8u2KLVAo8JGtzg5MU9DUyc3sUKjQlPT2jexQCOtNC@5JDM/T6NUp0yzuDRXIyu6TNvQqjRWU6dCpzi1EKTwv7GCkYKhguV/AA "R – Try It Online")
Main idea to to generate a way-long-enough cycling index vector you can use to get the needed elements from the input vector.
Original version:
```
function(x,i=seq(x),j=rep(i,max(x))){for(k in i){T=c(T,sum(x[j[(k+1):(k+x[k])]]))};T[-1]}
```
[Try it online!](https://tio.run/##JcmxCsIwGATg3afo@B/@DrE6qOQtsoUMJTSQhqaaWgiUPntM7XDHfVwqTha3RPv1U6TMXs79hzJ4kKl/k@exy5XA6qZEofGx8ViVtKR4XkbKetAUzgLP2lkHA2OA7aX0RZitOLLU8pUFP4DTLlHV8o3vNcdz@L@B8gM "R – Try It Online")
[Answer]
# Pyth, ~~13~~ 11 bytes
```
.esm@Q+dkSb
```
Saved 2 bytes thanks to Mr. Xcoder.
[Try it here](https://pyth.herokuapp.com/?code=.es%3C%3E%2ahsQQhkb&input=%5B1%2C2%2C3%2C4%2C5%2C4%2C3%2C2%2C1%2C2%2C3%2C4%2C3%2C2%2C1%5D%0A&debug=0)
### Explanation
```
.esm@Q+dkSb
.e         Q   For each index k and value b in (implicit) input...
         Sb    ... get the list [1, ..., b]...
   m  +dk      ... add k to each...
    @Q         ... and index into the input...
  s            ... then take the sum.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
ＩＥθΣＥι§θ⊕⁺κλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyG4NBfMzNRRcCzxzEtJrQCJeuYlF6XmpuaVpKZoBOSUFmtk6yjkaEKB9f//0dHmOhY6ZjqmOiY6xjpGOoY6prGx/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
  θ             Input array
 Ｅ              Map over elements
     ι          Current element
    Ｅ           Map over implicit range
           λ    Inner index
          κ     Outer index
         ⁺      Sum
        ⊕       Increment
       θ        Input array
      §         Cyclically index
   Σ            Sum
Ｉ               Cast to string
                Implicitly print on separate lines
```
[Answer]
# JavaScript ES6, 65 bytes
```
a=>a.map((x,y)=>{for(s=0,i=y;i<y+x;)s+=a[++i%a.length];return s})
```
Straightforward solution. Ungolfed:
```
a => a.map((x,y) => {
    var s = 0;
    for (i = y; i < y + x; i++) {
        s += a[i % a.length];
    }
    return s;
});
```
JavaScript's `map()` function is perfect for the job, it runs the given callback against each element and replaced it by the result of the callback. The callback receives two parameters, the first `x` is the value and the second `y` is the index. By taking the modulus `i % a.length` we can easily loop over the array, multiple times if needed.
### Test snippet
(Put the input as JSON notation)
```
let f = a=>a.map((x,y)=>{for(s=0,i=y;i<y+x;)s+=a[++i%a.length];return s})
```
```
<input id=I type="text" size=70 value="[4,3,2,1]"><button onclick="console.log(f(JSON.parse(I.value)))">Run</button>
```
[Answer]
# Java 8, 87 bytes
A curried void lambda taking an `int[]` list and `int` length.
```
l->s->{for(int i=-1,j,t;++i<s;System.out.println(t))for(j=t=0;j++<l[i];)t+=l[(i+j)%s];}
```
[Try It Online](https://tio.run/##rVJLa@MwED7Hv0KXgowdsUmbkx@wLCwUGnahx5CDKstBriIZaZwlBP/2rCzbrdsmFEpPFjPffI/xVPRA57rmqiqez3XzJAVDTFJr0ZoKhU7BbChaoOA@pVBUospNkQaEJGWjGAityO/hkQoFm218CfJLK9vsuUnvFfAdN3mOSpQFZznP7Tw/ldpgN4xENl/EVQxJFInUJo9HC3xPdAOkNq4vFYYw7MBVBtmPpIqiVG7ENgkhyuQGi6gKb@w2ac/BLAmcf6OBM@DFGKGP19N2Aa8h1po9/@0UH8Fw2kMn2NeAD8JC@uepcvUcGc64OLh@hhT/N0H9NIYePTTHYWdsNq72oEWBxmw9D9Jhrzcb@QgtCqzdoKu10@krPpjk1OCR5apZcD5HieSN4GcBeiw0RnU0g6/B26Wbeb9O90MHiXcdT97RvGXxW9q7o8QOJtRus0XU7GyfsCS0ruURd3T@ANHpLka3MVrGaNGGhDLGa8B33rePJKnakQu3NSkNK/QzlwVeNJavGqvv1Fh49luvtJroTesfUi6@bKEN2uD8Hw). Note that I've shadowed `System.out` in this program in order to grab results for prettier printing.
[Answer]
# [Julia 0.6](http://julialang.org/), 63 55 53 bytes
```
A->[sum(repmat(A,v+1)[i+1:i+v])for(i,v)=enumerate(A)]
```
[Try it online!](https://tio.run/##HYjLCsMgEAB/pcdd3BzU9EEhAb9DPCzBgiXaYNTft7aHGZh51z3wrW9LN9Nqzxoh@yNyAUNNSLRByGcQzeHrkyFQw8WnGn3m4sGg65EP4Gk9ckhlT7ABI9IFrCTlyCqSw5I03Un/@kGK5oH@M9N1bMT@BQ "Julia 0.6 – Try It Online")
---
Older solution:
# [Julia 0.6](http://julialang.org/), 65 bytes
```
A->(l=length(A);[sum(A[mod1(j,l)]for j∈i+1:i+A[i])for i∈1:l])
```
[Try it online!](https://tio.run/##LYpLCoQwEESv4rIb20Wb@eGgkHOELILzS0iiOHoHzzkXySTgoop6j3Kbt@aSxj7JZgDf@2d8rx@QeFffLYBUYXowOPKoX9NSud@@25o7W0tlNRZls@LOa0zBzGCaYV5sXH2EEQwiVaCYWhI5TKypUO722IKuJArf8uF0HEVe56wR0x8 "Julia 0.6 – Try It Online")
---
Another solution. Not great by bytecount, but I like it, and it's probably more efficient than the other two, especially if the input has big numbers.
# [Julia 0.6](http://julialang.org/), 69 bytes
```
A->(l=length(A);[sum([A;A][i+1:i+A[i]%l])+A[i]÷l*sum(A)for i∈1:l])
```
[Try it online!](https://tio.run/##yyrNyUw0@59s@99R104jxzYnNS@9JEPDUdM6urg0VyPa0doxNjpT29AqU9sxOjNWNSdWE8w4vD1HC6TAUTMtv0gh81FHh6EVUO5/bmKBRqKuXUFRZl5JTp5GskaipqaOgka0oY6RjjEQG@oYxuqAeEDSCMo21jHXMQbxLYAKTKAKjYEsU6CwpuZ/AA "Julia 0.6 – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 10 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
²Ｘ｛ｘ＋⁸＠］∑］
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JUIyJXVGRjM4JXVGRjVCJXVGRjU4JXVGRjBCJXUyMDc4JXVGRjIwJXVGRjNEJXUyMjExJXVGRjNE,i=JTVCNCUyQzQlMkMzJTJDMiUyQzIlNUQ_,v=3)
Explanation:
```
{         ] map over the items in the input
 ²X           save this loops counter on X (because of a bad design choice..)
   {    ]     map over 1..current item
    x+          add to it X
      ⁸@        and index in the input using that
         ∑    sum the map
```
[Answer]
# [QBasic 1.1](http://www.qbasic.net/), 115 bytes
```
INPUT L
DIM A(L)
FOR I=0TO L-1
INPUT C
A(I)=C
NEXT
FOR I=0TO L-1
S=0
FOR C=I+1TO I+A(I)
S=S+A(C MOD L)
NEXT
?S
NEXT
```
First input is the length **L**, then **L** subsequent inputs are the elements in order. **L** outputs represent the resulting array, with the elements in the order they're presented.
[Answer]
# Japt, 7 bytes
```
ËÆg°EÃx
```
[Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=y8ZnsEXDeA==&input=WzMsMiwxLDld)
[Answer]
# JavaScript, 46 bytes
```
a=>a.map(g=(x,y)=>x--&&a[++y%a.length]+g(x,y))
```
[Try it online](https://tio.run/##HclLCoAgFADA0ySGH6hWLfQi4uJhaoWpZISd3qLZzg43FHNu@WIxLbY50UBI4Adk7AWu9OmFrIwhBIqQpwMebPTXqon/s28mxZKC5SF57LCa6EgHOutvXg)
[Answer]
# APL+WIN, 37 bytes
Prompts for input:
```
+/¨v↑¨⊂[2](⍳⍴v)⌽((⍴v),⍴n)⍴n←(+/v)⍴v←⎕
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5r6x9aUfaobeKhFY@6mqKNYjUe9W5@1LulTPNRz14NDTBLB0jmaYIIoDYNbf0yEBuoZwLQqP9AQ/6ncRlZKBgpmACxMRibKJgqGHOlcRnCeSZgGRgfzAYA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
n←(+/v)⍴v←⎕ prompts for input and creates a repeating vector of length max v
((⍴v),⍴n)⍴n converts n to a matrix of length v x length n
(⍳⍴v)⌽ rotates each row of n by the size of each element of v
⊂[2] converts each row of m to an element in a nested vector
+/¨v↑¨ selects the number of elements from each element of the nested vector according to v and sums
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->a{w=0;a.map{|x|(a*-~x)[w+=1,x].sum}}
```
[Try it online!](https://tio.run/##VY7NDsIgEITvPgVHf7aNUKo1Bl@EcMBDT23S2DTFAL46ll05eJuZfDO7r@X5Tr1K1cP6VZ3vth7t5IMLe3usPu6g15Pi4Ew9L2OMSWsJDQjgBnYaBdyy5Fsqoc1SAiGCkPaf/9UpuEIHl40oIfZFh5jADFehoRPFFpw8zZv8N/NhCGxivR5MTF8 "Ruby – Try It Online")
[Answer]
# **JavaScript, 65 bytes 3̶0̶0̶ ̶b̶y̶t̶e̶s̶**
golfed
```
n=>n.map((z,x)=>{for(s=0,i=x;i<z+x;)s+=n[++i%n.length];return s})
```
ungolfed
```
     f = n=>n.map((z,x)=>{
            for(s=0,i=x;i<z+x;)s+=n[++i%n.length];
            return s
            }
        );
console.log(f(process.argv[2].slice(1, -1).split(", ").map(x=>+x)))
```
[Try it online!](https://tio.run/##Hc3RCsIgFADQX5Eg8KKTbU/Bcj8y9iDLLcOu4rUhi77dovcD52F2Q0tyMTcYbrauuqIeUT1N5PyQBfT4XkPipFvpdBnc9RBlABIaJyHcGZW3uOX7PCSbXwkZfaAuASl4q3zY@MpjCoslUiZt@9TPirxbLO8kazpQFL3L/CTZCf5n0aMoAFDr1EvWSvZzl/kL "JavaScript (Node.js) – Try It Online")
(ungolfed version above)
I'm new to this codegolf thing!
---
\*updated! thanks to the useful links provided in comments, I managed to reduce the size to 65 bytes!
[Answer]
## [Perl 5](https://www.perl.org/) with `-M5.010`, 42 bytes
```
say sum+((@F,@F)x$_)[++$-..($-+$_-1)]for@F
```
[Try it online!](https://tio.run/##TY/BbsIwEETv@QqL@pDI65CEuKWgSjnlBEdOCKEgbSWraYLsrYCfr7s1ROKyO7PzPJLP6HoTpP4o1uJFOPRI4nN0gtCT8D@WMPjuxupbpWnTQtNmV3nM9kpJneep1EoedZkd@E3ThjWzs9l/E17JdaK3A4qTw@5LnJAuiEMs9qGGBVRQJnHCe1Kyr8EkNdyTihPzxDx4dm@whFfOpotJqmUEqniINbDgwklP4N1H/TueyY6DD3ro2jnMg96avCgL3hvrabXake1Vyp/O/gA "Perl 5 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-rn`, 14 bytes
```
$+g@(_+\,B)MEg
```
Takes input numbers on successive lines of stdin; gives output numbers on successive lines of stdout. [Try it online!](https://tio.run/##K8gs@P9fRTvdQSNeO0bHSdPXNf3/f0MuYy4TLtP/ukV5AA "Pip – Try It Online")
### Explanation
```
             g  List of lines of stdin (from -r flag)
           ME   Enumerate and map this function to the (index, value) pairs:
       \,B       One-based range(value)
     _+          To each element, add the index of that value
  g@(     )      Use the resulting range to slice into the original list g
                 (cyclical indexing is built in)
$+               Sum the numbers in the slice
                Output the list of results one per line (from -n flag)
```
Or, using a worked example:
```
             g  [1 3 4 5]
           ME
       \,B      [(1,2) (1,4) (1,5) (1,6)]
     _+         [(1,2) (2,5) (3,7) (4,9)]
  g@(     )     [[3] [4 5 1] [5 1 3 4] [1 3 4 5 1]]
$+              [3 10 13 14]
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 12 bytes
```
+/¨⊢⍴¨⍳∘≢⌽¨⊂
```
[Try it online!](https://tio.run/##fZDNSsNAFIX38xR3l0Updv6ciW8TKpFgINJ2U6SbImKtETeCW7tyr24ENz7KfZF4ZqYRlMYQJpOZ755z7i0u6vHpsqibs/G0Lubzatrx/WPV8PWD7Eqso6OvF77dcfuGb/vKN0@82fHdZzhdd90CyCW377x5nmFbcvtxkjXnGW@vsrKo6gwHuJ6thCFNiiQdfhYkJ@TIkhEJy4dBFdictBYSmgZFQ6gOpMRqYJ8CqCFVGV5Px@SRwP4TNkaVBiQUY9q@NXmAzdGVAxHutXDRwf5U2D@0Cm2Rgr7t4yDKRCgfbVQsSz3rX4m0A4pcNhpiRNqThpjBjPqK3jT9pz0sAx9GFKr8vnMXZWLqbw "APL (Dyalog Classic) – Try It Online")
uses `⎕io←1`
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~50~~ 32 bytes
```
{$_>>.&{.[++$+ ^$^a X%+$_].sum}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiXezk5PrVovWltbRVshTiUuUSFCVVslPlavuDS3tva/dXEiSKlGtImOsY6RjmGspjUXTAgsoGOJLGQIVGWiY4osZKID0WqEqtUUu3lQa1AlzHUsdMyAOmCSKOYbWYC1GYHlwLbrGKM6CSYM0w7hw6z/DwA "Perl 6 – Try It Online")
~~I'm new to golfing in Perl 6, so I'm sure this can be shorter.~~ Not new anymore, and back to golf this!
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ıRṅ+iS
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCVCMVIlRTElQjklODUlMkJpUyZmb290ZXI9JmlucHV0PSU1QjQlMkMzJTJDMiUyQzElNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwJTVCMTAlMkM3JTJDNSUyQzQlNUQlMEElNUIzJTJDMiUyQzElMkM5JTVEJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLSUzRSUyMCU1QjEyJTJDMTAlMkM5JTJDMzMlNUQlMEElNUIxJTJDMyUyQzQlMkM1JTVEJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLSUzRSUyMCU1QjMlMkMxMCUyQzEzJTJDMTQlNUQlMEElNUI0JTJDNCUyQzMlMkMyJTJDMiU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAlNUIxMSUyQzExJTJDOCUyQzYlMkM4JTVEJTBBJTVCMyUyQzUlMkMzJTJDMiUyQzElNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwJTVCMTAlMkMxNCUyQzYlMkM0JTJDMyU1RCUwQSU1QjMlMkMyJTJDNCUyQzMlMkMyJTJDMSUyQzElNUQlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAtJTNFJTIwJTVCOSUyQzclMkM3JTJDNCUyQzIlMkMxJTJDMyU1RCUwQSU1QjclMkM4JTJDNiUyQzUlMkM0JTJDMyUyQzIlMkMxJTJDNSU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAlNUIyOSUyQzMzJTJDMjAlMkMxNSUyQzExJTJDOCUyQzYlMkM1JTJDMzAlNUQlMEElNUIyOCUyQzIlMkM0JTJDMiUyQzMlMkMyJTJDMyUyQzQlMkM1JTJDMyU1RCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC0lM0UlMjAlNUIxMzclMkM2JTJDMTAlMkM1JTJDOSUyQzclMkMxMiUyQzM4JTJDMzklMkMzNCU1RCUwQSU1QjElMkMyJTJDMyUyQzQlMkM1JTJDNCUyQzMlMkMyJTJDMSUyQzIlMkMzJTJDNCUyQzMlMkMyJTJDMSU1RCUyMC0lM0UlMjAlNUIyJTJDNyUyQzEzJTJDMTQlMkMxMiUyQzglMkM1JTJDMyUyQzIlMkM3JTJDOSUyQzclMkM0JTJDMiUyQzElNUQmZmxhZ3M9Qw==)
#### Explanation
```
ıRṅ+iS  # Implicit input
ı       # Map over the input:
 R      #  [1..item]
  ṅ+    #  Plus 0-based index
    i   #  Index into input
     S  #  Sum the list
        # Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
ėƛ÷$?$›ǓẎ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+UCIsIiIsIsSXxpvDtyQ/JOKAuseT4bqO4oiRIiwiIiwiWzQsMywyLDFdICAgICAgICAgICAgICAgICAgICAgICAtPiBbMTAsNyw1LDRdXG5bMywyLDEsOV0gICAgICAgICAgICAgICAgICAgICAgIC0+IFsxMiwxMCw5LDMzXVxuWzEsMyw0LDVdICAgICAgICAgICAgICAgICAgICAgICAtPiBbMywxMCwxMywxNF1cbls0LDQsMywyLDJdICAgICAgICAgICAgICAgICAgICAgLT4gWzExLDExLDgsNiw4XVxuWzMsNSwzLDIsMV0gICAgICAgICAgICAgICAgICAgICAtPiBbMTAsMTQsNiw0LDNdXG5bMywyLDQsMywyLDEsMV0gICAgICAgICAgICAgICAgIC0+IFs5LDcsNyw0LDIsMSwzXVxuWzcsOCw2LDUsNCwzLDIsMSw1XSAgICAgICAgICAgICAtPiBbMjksMzMsMjAsMTUsMTEsOCw2LDUsMzBdXG5bMjgsMiw0LDIsMywyLDMsNCw1LDNdICAgICAgICAgIC0+IFsxMzcsNiwxMCw1LDksNywxMiwzOCwzOSwzNF1cblsxLDIsMyw0LDUsNCwzLDIsMSwyLDMsNCwzLDIsMV0gLT4gWzIsNywxMywxNCwxMiw4LDUsMywyLDcsOSw3LDQsMiwxXSJd)
#### Explanation
```
ėƛ÷$?$›ǓẎ∑  # Implicit input
ėƛ          # Enumerate (index, item) and map over:
  ÷$        #  Dump onto stack and swap
    ?$›Ǔ    #  Rotate input left by (index + 1)
        Ẏ∑  #  Take the first (item) elements and sum
            # Implicit output
```
]


[Question]
      [
In this challenge you will be converting a mixed number to an improper fraction.
Because improper fractions use fewer numbers, your code will need to be as short as possible.
---
## Examples
```
4 1/2
9/2
12 2/4
50/4
0 0/2
0/2
11 23/44
507/44
```
## Specification
You may assume the denominator of the input will never be 0. The input will always be in the format `x y/z` where x,y,z are arbitrary nonnegative integers. You do not need to simplify the output.
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins.

[Answer]
# LabVIEW, 29 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
[![](https://i.stack.imgur.com/TvVku.gif)](https://i.stack.imgur.com/TvVku.gif)
[Answer]
## CJam, ~~16~~ ~~15~~ 14 bytes
```
l'/']er~:Xb'/X
```
or
```
l'/']er~_@b'/@
```
[Test it here.](http://cjam.aditsu.net/#code=l'%2F'%5Der~%3AXb'%2FX&input=11%2023%2F44)
## Explanation
```
l      e# Read input.
'/']er e# Replace the "/" with a "]".
~      e# Evaluate the string as code. If the input was "i n/d", this pushes [i n] d.
:X     e# Store the denominator in X.
b      e# Treat [i n] as base-d digits. This effectively computes i*d + n.
'/     e# Push a slash.
X      e# Push the denominator.
```
The other version avoids using a variable by using a bit more stack shifting.
[Answer]
## Mathematica, 58 bytes
```
ToExpression@StringReplace[#," "->"+"]~ToString~InputForm&
```
This returns the simplified result. If outputting a rational number instead of a string is fine, we can save 19 bytes:
```
ToExpression@StringReplace[#," "->"+"]&
```
[Answer]
## PowerShell, ~~47~~ ~~44~~ 42 Bytes
[Crossed out 44 is still regular 44 ;(](http://meta.codegolf.stackexchange.com/a/7427/42963)
```
$l,$n,$d=$args-split'\D';"$(+$l*$d+$n)/$d"
```
Golfed a couple bytes by using regex `-split`. Golfed a couple more thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) by swapping the regex.
The `$args-split'\D'` takes our input argument and splits on non-digit characters. Here it performs two splits, one on whitespace, the other on the `/` character. The results are then stored in the three variables using a simultaneous assignment. We then formulate the string output as (the `$l`eft number times the `$d`enominator plus the `$n`umerator) executed as a code block, a `/` slash, and then the `$d`enominator again.
[Answer]
# Java with [Ten Foot Laser Pole](https://github.com/SuperJedi224/Ten-Foot-Laser-Pole) 1.03, 79+25 (import) = 104 bytes
Requires `import sj224.tflp.math.*;`
```
String m(String[]a){return ""+new BigRational(a[0]).add(new BigRational(a[1]));}
```
This will almost certainly work with 1.04 as well, but so far I've only tested it with 1.03 because I already happened to have a java project set up with 1.03 in the build path.
[Answer]
# JavaScript (ES6), ~~44~~ 41 bytes
```
m=>([x,y,z]=m.match(/\d+/g),+y+x*z+"/"+z)
```
*Saved 3 bytes thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions)!*
## Explanation
Very simple.
```
m=>
  ([x,y,z]=m.match(/\d+/g), // x, y and z = numbers from input
    +y+x*z                  // numerator
    +"/"+z                  // denominator
  )
```
## Test
Test is without destructuring assignment to work in most browsers.
```
var solution = m=>+(p=m.match(/\d+/g))[1]+p[0]*p[2]+"/"+p[2]
```
```
<input type="text" id="input" value="11 23/44" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Japt, 10 bytes
Woohoo, currently beating CJam!
```
U*W+V+'/+W
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=VSpXK1YrJy8rVw==&input=MTEgMjMvNDQ=)
### How it works
```
       // Implicit: [U,V,W] = eval(input). This automatically discards the slash.
U*W+V  // Calculate the new numerator: (whole part * denominator) + numerator.
+'/+W  // Add the slash and the denominator.
       // Implicit: output last expression
```
[Answer]
# Julia, ~~58~~ 50 bytes
```
s->eval(parse((r=replace)(r(s," ","+"),"/","//")))
```
This is an anonymous function that accepts a string and returns a `Rational` type object. To call it, give it a name, e.g. `f=s->...`.
We can take advantage of the fact that the input can be manipulated slightly to be an expression that evaluates to a rational. In particular, an integer plus a rational is a rational, and rationals are denoted with double slashes. So if we turn `4 1/2` into `4+1//2`, the evaluated result will be `9//2`.
Ungolfed:
```
function f(s::AbstractString)
    # Replace the space in the input with a plus
    r1 = replace(s, " ", "+")
    # Replace the / with //
    r2 = replace(r1, "/", "//")
    # Parse the resulting expression as a rational
    return eval(parse(r2))
end
```
[Answer]
# Smalltalk – 76 characters
The input exactly matches the array delimiter and inherent fraction representation of Smalltalk. If it just weren't so verbose, it could have been a serious contender!
```
Compiler evaluate:'|p|p:=0.#(',FileStream stdin nextLine,')do:[:q|p:=p+q].p'
```
It's too bad simplification wasn't a requirement, Smalltalk does it automatically!
[Answer]
# Bash + coreutils, 28
```
dc<<<${@/\// }sarla*+n47Plap
```
`$@` expands to all command-line parameters, so `${@/\// }` expands to all command-line parameters with `/` replaced with , which is put on `dc`'s stack. The rest is simple stack manipulation and arithmetic.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#`'/¡R`Š©*+®'/ý
```
-2 bytes thanks to *@MagicOctopusUrn*.
[Try it online](https://tio.run/##MzBNTDJM/f9fOUFd/9DCoISjCw6t1NI@tE5d//De//9NFAz1jQA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/i9l85QV3/0MKghKMLDq3U0j60Tl3/8N7/Ov9NFAz1jbgMjRSM9E24DBQMQBxDBSNjfRMTAA).
**Explanation:**
```
#`         # Split input by spaces and push all items to the stack
           #  i.e. "4 1/2" → "4" and "1/2"
  '/¡      # Push the second item by "/"
           #  i.e. "1/2" → [1,2]
     R`    # Revert the list, and also push all items to the stack
           #  i.e. [1,2] → [2,1] → 2 and 1
Š          # Triple-swap the stack
           #  [4,2,1] → [1,4,2]
 ©         # Store the 2 in the register
  *        # Multiple the top two items
           #  4 and 2 → 8
   +       # Add the top two items
           #  1 and 8 → 9
®          # Push the 2 from the register to the stack again
 '/ý       # Join the two items by "/"
           #  9 and 2 → "9/2"
```
---
With flexible input- and output-format, taking the integers in the order `x,z,y` and outputting the nominator and denominator on separated lines it would be **4 bytes** (which is why I added the [parsing](/questions/tagged/parsing "show questions tagged 'parsing'")-tag to the challenge..):
```
*+²»
```
[Try it online](https://tio.run/##MzBNTDJM/f9fS/vQpkO7//834TLiMgQA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/i5ul5aOV/Le1D6w7t/q9zaJv9fxMuIy5DLkMjLhDDAIwNDblMgDxjAA).
**Explanation:**
```
*        # Multiply the first two inputs (x and z)
         #  i.e. 4 and 2 → 8
 +       # Add the third input (y)
         #  i.e. 8 and 1 → 9
  ²      # Take the second input again (z)
   »     # Join the stack by newlines and implicitly print it
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~74~~ ~~67~~ 63 bytes
```
r=read
f x|(a,(c,s:d):_)<-lex<$>lex x!!0=show(r a*r d+r c)++s:d
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v8i2KDUxhStNoaJGI1FHI1mn2CpF0ype00Y3J7XCRsUOSCpUKCoa2BZn5JdrFCkkahUppGgXKSRramsDlf7PTczMsy0oyswrUUlTMjRSMNY3UfoPAA "Haskell – Try It Online")
## Explanation
As [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) figured out we can use Haskell's lexer here to break up the string into it's parts. (Earlier I was using `span(>'/')`) And Laikoni pointed out that `<$>` works just like `mapSnd` from `Data.Tuple`.
The pattern guard breaks up our code into the three numbers we want using `lex`. `lex` invokes haskell's lexer to break off the first token. It returns a list with each element representing a possible way to parse the string. These elements are tuples with the first element being the first token and the rest of the string being the second element. Now since the input format is very regular we are only ever going to have exactly one parse, so we can always take the first one. The first thing we do is invoke `lex` on the input
```
lex x
```
Then we unwrap it from it's list giving us a 2-tuple
```
lex x!!0
```
The first token will be the whole part of the mixed fraction leaving the fraction prepended by a space to still parse. Then since tuples are `Functors` we can use `(<$>)` an alias for `fmap` to apply `lex` to the second element of the tuple.
```
lex<$>lex x!!0
```
This eats through the space and breaks off the next token, the numerator of our fraction. Now we bind this to a pattern match using `<-`. Our pattern is
```
(a,(c,s:d):_)
```
`a` grabs the whole part of the fraction, our first token. `:_` unwraps the list resulting from our second `lex`. `c` grabs the second token we lexed, that is the numerator of the fraction. Everything that remains is bound to `s:d` which splits it into its first character, guaranteed by the format to be a `/` and the remainder which will be the denominator.
Now that we have parsed the input we do the actual computation:
```
show(r a*r d+r c)++s:d
```
Where `r` is the read function we bound earlier.
It is important to note that `lex` returns a list empty if it fails and non-empty if it succeeds. Why this is not a `Maybe` I do not know.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 1 byte
```
+
```
[Run and debug it](https://staxlang.xyz/#c=%2B&i=4+1%2F2%0A12+2%2F4%0A0+0%2F2%0A11+23%2F44&a=1&m=2) (although there's not much to debug)
The challenge specification says "You do not need to simplify the output." Assuming it's *allowed* to simplify, then there's a built-in instruction in stax to do this. The input is implicitly interpreted as an integer and a rational number. The `+` instruction widens both to rationals, adds, and simplifies. The result is implicitly printed.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 92 bytes
```
: f 0 -rot 3. do 0 -rot >number 1 m+ loop 2drop + >r swap i * + r> <# 0 #s '/ hold + #s #> ;
```
[Try it online!](https://tio.run/##ZY3LCsIwFET3fsXQLARLzaNdqeRf1DRWaL3hJiJ@fbwuBNHNDOfAMJG4TN0lvqvWHSIMOqaCfotAH/C3@3IaGRZLi5kowQWWbOEZ@XFMuGIjxB4HJSOVsdaYaA4iBZTHvuYG1sL1ehga@SnPNOLMK9EDrHY/zsD8Oevg9Pe4vgA "Forth (gforth) – Try It Online")
The pain of parsing and formatting...
Takes a string as `pointer length` (gforth standard), and returns a string in the same format.
### How it works
```
: f ( addr u -- addr u )  \ take a string and return a string
  0 -rot      \ ( 0 addr u )
  3. do       \ repeat 3 times...
    0 -rot      \ ( ... 0 0 addr u )
    >number     \ ( ... num 0 addr u ) parse an integer;
                \ `addr` now points to right after the parsed int
    1 m+        \ increment the addr to point to the next integer
  loop        \ end loop ( x y z 0 addr u )
  2drop +     \ discard input string and zero on the top
  >r          \ ( x y R:z ) so the value of z can be copied by `i`
  swap i * +  \ ( x*z+y R:z )
  r>          \ ( x*z+y z )
  <#          \ start formatting the output from the end
  0 #s        \ push z to the output; formatting built-ins take double cells
  '/ hold     \ push a slash
  + #s        \ #s leaves two zeros at the top, so discard one and push x*z+y
  #>          \ finish formatting and get the string ( pointer length )
;
```
[Answer]
# Wolfram|Alpha, 0 or 1 byte
```
=
```
The challenge says it's not necessary to simplify the output, but doesn't disallow it. If it's not disallowed, then:
1)The online Wolfram|Alpha interpreter will automatically convert mixed numbers to improper fractions (0 bytes). E.g.:
[![enter image description here](https://i.stack.imgur.com/sm5uP.png)](https://i.stack.imgur.com/sm5uP.png)
2)The Wolfram|Alpha interpreter can be called within Mathematica by entering `=` followed by the input (1 byte):
[![enter image description here](https://i.stack.imgur.com/vJq6F.png)](https://i.stack.imgur.com/vJq6F.png)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 18 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
OẸ'//ẸsNṭẊ,p+x,'/j
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPU8lRTElQkElQjgnJTJGJTJGJUUxJUJBJUI4c04lRTElQjklQUQlRTElQkElOEElMkNwJTJCeCUyQyclMkZqJmZvb3Rlcj0maW5wdXQ9JTIyNCUyMDElMkYyJTIyJTIwJTIwJTIwJTIwLSUzRSUyMCUyMjklMkYyJTIyJTBBJTIyMTIlMjAyJTJGNCUyMiUyMCUyMCUyMC0lM0UlMjAlMjI1MCUyRjQlMjIlMEElMjIwJTIwMCUyRjIlMjIlMjAlMjAlMjAlMjAtJTNFJTIwJTIyMCUyRjIlMjIlMEElMjIxMSUyMDIzJTJGNDQlMjIlMjAtJTNFJTIwJTIyNTA3JTJGNDQlMjImZmxhZ3M9Q2U=)
#### Explanation
```
OẸ'//ẸsNṭẊ,p+x,'/j  # Implicit input ("x y/z")
OẸ                  # Split on spaces, then dump onto the stack
  '//Ẹ             '# Split the fraction on "/", then dump again
      sN            # Swap and convert the numerator to integer
        ṭ           # Triple swap to get the order [y, x, z]
         Ẋ          # Copy z to the register without popping
          ,p        # Multiply x and z (implicit conversion to int)
            +       # Add this to y (which we converted earlier)
             x,     # Pair this with z (from the register)
               '/j '# Join this pair on "/"
                    # Implicit output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
⌈E∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLijIhF4oiRIiwiIiwiNCAxLzIiXQ==) -4 thanks to lyxal
```
⌈   # Split on spaces
 E  # Evaluate each
  ∑ # Sum
```
[Answer]
# [Factor](https://factorcode.org), 43 bytes
```
[ eval( -- x x ) + >fraction [I ${}/${}I] ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=JU29CsIwGNz7FEcQVEpJGzOIgrhJFxfRpXQIkmogJiVG8QefxKWLPoBv49sYDB_HHXfcfc93I7beuu67Wa_K5WICeRYaB-H3UMZL11otvMROGumEVjfhlTVHKItpkhCOgjKSkIKBUR5EjjwaBdiIck5eJ99k429a_YcHyDJcwg2RYta48DvMoSrRuz9oQFmjjpVPv8IcRqMGhxFtq68x6LrIPw)
Assumes the input must be a string, otherwise this can be shorter. Simplifies the output.
[Answer]
# Javascript ES6, 62 bytes
```
p=prompt;b=p(a=+p()).split`/`;alert((+b[1]*a+ +b[0])+"/"+b[1])
```
[Answer]
# Perl, ~~82~~ ~~61~~ 38 bytes
```
#!perl -paF/\D/
$_=$F[0]*$F[2]+$F[1]."/$F[2]"
```
This can probably be golfed more.
**Changes**
* Saved 16 bytes by using a regex in `split`, and 5 by using `<>` instead of `<STDIN>`.
* Saved another 16 bytes thanks to Dennis.
[Answer]
## Mathematica, 51 bytes
```
Interpreter["ComputedNumber"]@#~ToString~InputForm&
```
Interestingly, Mathematica supports this with a built-in. If outputting a number is allowed, than we only need 28 bytes:
```
Interpreter@"ComputedNumber"
```
[Answer]
# Java, ~~159~~ ~~148~~ ~~142~~ ~~120~~ 110 bytes
```
String m(String[]a){Long b=new Long(a[0]),d=new Long((a=a[1].split("/"))[1]);return b*d+new Long(a[0])+"/"+d;}
```
Saved a bunch of bytes thanks to FlagAsSpam.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 23 bytes
```
->x{eval x.split*?++?r}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166iOrUsMUehQq@4ICezRMteW9u@qPZ/QWlJsUJatJKJgqG@kVLsfwA "Ruby – Try It Online")
[Answer]
# [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 13 bytes
```
a*c+b.."/"..c
```
[Try it online!](https://tio.run/##SyxKykn9/z9RK1k7SU9PSV9JTy/5////hob/jYz/m5gAAA "ARBLE – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~78~~ 76 bytes
```
def f(s):a,b=s.split();b,c=b.split('/');return'%s/'%(int(a)*int(c)+int(b))+c
```
[Try it online!](https://tio.run/##TY3BDoIwEETvfMVezHaFUECMEdIvUQ6AJZIaIG09EOO3Y4uYuJfZmbydnWZ7H4fDstxkBx0zVNRRI0xspkdvGZVN1Ipmc8iRSi3tUw@4Mxx3rB8sq2nvpaXQS0MUtouVxhoQ8MIcUp5hAXh2EgGmGWQ898ExceqSBJIvkWxECtmB5xtz8ts76EYNCvoB1uZYydkwKgJwM2n/V7lLgKt1DStyUdWafKOOKfqzDKXWo8YIR4V0@R0I4bmKguUD "Python 3 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) with -la -Mfeature=say, 32 bytes 25 bytes
```
m|/|;say$_*$'+$F[1],"/$'"
```
[Try it online!](https://tio.run/##K0gtyjH9/z@3Rr/GujixUiVeS0VdW8Ut2jBWR0lfRV3p/38TBUN9Iy5DIwUjfRMuAwUDEMdQwchY38TkX35BSWZ@XvF/3ZzE/7q@aamJJaVFqbZAcwA "Perl 5 – Try It Online")
*(-7 bytes thanks to Dom Hastings)*
`$_` is the whole input `x y/z`, which evaluates the value of `x` in numeric contexts (like the `*` here). `$'` is the regex post-match string, which here contains whatever comes after `/` - so, `z`. To get the `y` value, we use the `-a` flag which splits the input on spaces and places them in the `@F` array. So here, `@F = ("x", "y/z")`, which means `$F[1]="y/z"` which evaluates in `y` in numeric contexts (since `y` is the initial contiguous sequence of digits with `$F[1]`).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
Σmrw
```
[Try it online!](https://tio.run/##yygtzv7//9zi3KLy////mygY6hsBAA "Husk – Try It Online")
`ṁrw` is supposed to work, but there's some bug that returns an empty list. Anyway, hooray for native rational number support.
[Answer]
# [GNU AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 5+16 = 21 bytes
Command-line argument: `-F |/`
Source code:
```
$0=$1*$3+$2"/"$3
```
[Try it online!](https://tio.run/##SyzP/v9fxcBWxVBLxVhbxUhJX0nF@P9/EwVDfSMuQyMFI30TLgMFAxDHUMHIWN/E5F9@QUlmfl7xf103hRp9AA "AWK – Try It Online")
The command-line argument sets the field separator to the regex `/ |\//`. Thus, it is easy to map the input as three fields.
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 1 byte
`+`
Itr has built-in support for rational numbers, including for parsing input numbers.
[online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=Kw==&in=MTEgMjMvNDQ=)
## Explanation
```
   ; implicit input, by default numbers are separated by spaces
   ; two integers with a '/' between them are interpreted as a fraction
 + ; add the integer part to the fractional part
   ; implicitly output the fraction
```
[Answer]
# [Headass](https://esolangs.org/wiki/Headass), 80 bytes
```
-(----[]]]][]]][{{U]>)D^^D^^^^^R]^}:DON-)}:NE.U[UOUO{^)N+E:]OD-}.U^U[{U^)DPD]P:}
```
[Try It Online!](https://dso.surge.sh/#@WyJoZWFkYXNzIiwiIiwiLSgtLS0tW11dXV1bXV1dW3t7VV0+KUReXkReXl5eXlJdXn06RE9OLSl9Ok5FLlVbVU9VT3teKU4rRTpdT0QtfS5VXlVbe1VeKURQRF1QOn0iLCIiLCI0OSAvLyAxXG40OSAvLyAxXG4zMiAvLyBzcGFjZVxuNTAgLy8gMlxuNTEgLy8gM1xuNDcgLy8gL1xuNTIgLy8gNFxuNTIgLy8gNCIsIiJd) Takes character codes as input and outputs as two numbers Numerator, Denominator.
### Explanation:
Fairly straightforward, parses by looping through digits, subtracting 48, and then multiplying by 10 before adding each new number. when it hits a charcode less than 48, it knows to move on to the next number. There's not an easy way to multiply within a single code block to my knowledge, so the next two code blocks respectively copy a bunch of x onto the queue and then add them all up. Probably still golfable within the same approach, I found a few golfs while writing up the explanation, even.
```
-(----[]]]][]]][{{U]>)D^^D^^^^^R]^}:DON-)}:NE. block 0: parses input
-(                                             r3 = -1
  ----[]]]][]]][                               r2 = -48
                {                     N-)}:    while input remains
                 {U]>)            }:             while input + r2 > r3
                      D^^D^^^^^                    r1 *= 10
                               R]^                 r1 += input + r2
                                    DO           enqueue and reset r1
                                           NE  go to block 1
                                             . end block
U[UOUO{^)N+E:]OD-}. block 1: copies x z times onto queue
U[                  r2 = x
  UO                enqueue y
    UO              enqueue z
    U  ^            r1 = z
      {^)   :  D-}  while(r1--){
             ]O       enqueue x
                    }
         N+E        go to block 2
                  . end code block
U^U[{U^)DPD]P:} block 2: sums copies of x and adds y, prints x*z+y and z
U^              r1 = y
  U[            r2 = z
    {U )     :} while items remain unvisited on the queue (all of which are x)
     U^           r1 += x
        DP      print r1
          D]P   print r2
```
]