[Question]
  [
Or, "Swap the first and last letters of each word"
Your challenge is to, given a string of alphabetical ASCII characters as well as one other character to use as a delimiter (to separate each word), swap the first and last letters of each word. If there is a one-character word, leave it alone.
The examples/testcases use the lowercase letters and the space as the delimiter.
You do not need to handle punctuation; all of the inputs will only consist of the letters a through z, separated by a delimiter, all of a uniform case.
For example, with the string "hello world":
```
Input string: "hello world"
Identify each word: "[hello] [world]"
Identify the first and last letters of each word: "[[h]ell[o]] [[w]orl[d]]"
Swap the first letters of each word: "[[o]ell[h]] [[d]orl[w]]"
Final string: "oellh dorlw"
```
NOTE: the delimiter does not need to be inputted separately. The delimiter is just the character used to separate words. It can be anything. I wanted to leave options open for creative golfers, so I did not want to limit it to just spaces or new lines. The delimiter is just a character that separates words in the input string.
**Test cases:**
```
"swap the first and last letters of each word" -> "pwas eht tirsf dna tasl setterl fo hace dorw"
"hello world" -> "oellh dorlw"
"test cases" -> "test sasec"
"programming puzzles and code golf" -> "grogramminp suzzlep dna eodc folg"
"in a green meadow" -> "ni a nreeg weadom"
"yay racecar" -> "yay racecar"
```
  
[Answer]
# TeX, 216 bytes (4 lines, 54 characters each)
***Because it's not about the byte count, it's about the quality of the typeset output :-)***
```
{\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13%
\global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{%
I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D%
#2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }}
```
[Try it Online! (Overleaf; not sure how it works)](https://www.overleaf.com/read/dkypfbgxmhdw)
Full test file:
```
{\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13%
\global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{%
I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D%
#2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }}
\S{swap the a first and last letters of each word}
pwas eht a tirsf dna tasl setterl fo hace dorw
\S{SWAP THE A FIRST AND LAST LETTERS OF EACH WORD}
\bye
```
Output:
> 
> [![enter image description here](https://i.stack.imgur.com/846L5.png)](https://i.stack.imgur.com/846L5.png)
> 
> 
> 
---
For LaTeX you just need the boilerplate:
```
\documentclass{article}
\begin{document}
{\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13%
\global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{%
I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D%
#2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }}
\S{swap the a first and last letters of each word}
pwas eht a tirsf dna tasl setterl fo hace dorw
\S{SWAP THE A FIRST AND LAST LETTERS OF EACH WORD}
\end{document}
```
---
## Explanation
TeX is a strange beast. Reading normal code and understanding it is a feat by itself. Understanding obfuscated TeX code goes a few steps further. I'll try to make this understandable for people who don't know TeX as well, so before we start here's a few concepts about TeX to make things easier to follow:
### For (not so) absolute TeX beginners
* First, and most important item in this list: the code does *not* have to be in rectangle shape, [even though](https://tex.stackexchange.com/q/450795/134574) [pop culture](https://tex.stackexchange.com/a/156937/134574) [might lead you](https://tex.stackexchange.com/a/474872/134574) [to think so](https://tex.stackexchange.com/a/406914/134574).
* TeX is a macro expansion language. You can, as an example, define `\def\sayhello#1{Hello, #1!}` and then write `\sayhello{Code Golfists}` to get TeX to print `Hello, Code Golfists!`. This is called an “undelimited macro”, and to feed it the first (and only, in this case) parameter you enclose it in braces. TeX removes those braces when the macro grabs the argument. You can use up to 9 parameters: `\def\say#1#2{#1, #2!}` then `\say{Good news}{everyone}`.
* The counterpart of undelimited macros are, unsurprisingly, delimited ones :) You could make the previous definition a tad more *semantical*: `\def\say #1 to #2.{#1, #2!}`. In this case the parameters are followed by so-called *parameter text*. Such parameter text delimits the argument of the macro (`#1` is delimited by `␣to␣`, spaces included, and `#2` is delimited by `.`). After that definition you can write `\say Good news to everyone.`, which will expand to `Good news, everyone!`. Nice, isn't it? :) However a delimited argument is (quoting the *TeXbook*) “the shortest (possibly empty) sequence of tokens with properly nested `{...}` groups that is followed in the input by this particular list of non-parameter tokens”. This means that the expansion of `\say Let's go to the mall to Martin` will produce a weird sentence. In this case you'd need to “hide” the first `␣to␣` with `{...}`: `\say {Let's go to the mall} to Martin`.
* So far so good. Now things start to get weird. When TeX reads a character (which is defined by a “character code”), it assigns that character a “category code” (catcode, for friends :) which defines what that character will mean. This combination of character and category code makes a token (more on that [here](https://tex.stackexchange.com/a/104050/134574), for example). The ones which are of interest for us here are basically:
	+ **catcode 11**, which define tokens which can make up a control sequence (a posh name for a macro). By default all letters [a-zA-Z] are catcode 11, so I can write `\hello`, which is one single control sequence, while `\he11o` is the control sequence `\he` followed by two characters `1`, followed by the letter `o`, because `1` is not catcode 11. If I did `\catcode`1=11`, from that point on `\he11o` would be one control sequence. One important thing is that catcodes are set when TeX first sees the character at hand, and such catcode is *frozen*... FOREVER! (terms and conditions may apply)
	+ **catcode 12**, which are most of other characters, such as `0"!@*(?,.-+/` and so forth. They are the *least* special type of catcode as they serve only for writing stuff on the paper. But hey, who uses TeX for writing?!? (again, terms and conditions may apply)
	+ **catcode 13**, which is hell :) Really. Stop reading and go do something out of your life. You don't want to know what catcode 13 is. Ever heard of Friday, 13th? Guess where it got its name from! Continue at your own risk! A catcode 13 character, also called an “active” character, is not just a character anymore, it is a macro itself! You can define it to have parameters and expand to something like we saw above. After you do `\catcode`e=13` you *think* you can do `\def e{I am the letter e!}`, BUT. YOU. CANNOT! `e` is not a letter anymore, so `\def` is not the `\def` you know, it is `\d e f`! Oh, choose another letter you say? Okay! `\catcode`R=13 \def R{I am an ARRR!}`. Very well, Jimmy, try it! I dare you do that and write an `R` in your code! That's what a catcode 13 is. I AM CALM! Let's move on.
* Okay, now to grouping. This is fairly straightforward. Whatever assignments (`\def` is an assignment operation, `\let` (we'll get into it) is another) done in a group are restored to what they were before that group started unless that assignment is global. There are several ways to start groups, one of them is with catcode 1 and 2 characters (oh, catcodes again). By default `{` is catcode 1, or begin-group, and `}` is catcode 2, or end-group. An example: `\def\a{1} \a{\def\a{2} \a} \a` This prints `1 2 1`. Outside the group `\a` was `1`, then inside it was redefined to `2`, and when the group ended, it was restored to `1`.
* The `\let` operation is another assignment operation like `\def`, but rather different. With `\def` you *define* macros which will expand to stuff, with `\let` you create copies of already existing things. After `\let\blub=\def` (the `=` is optional) you can change the start of the `e` example from the catcode 13 item above to `\blub e{...` and have fun with that one. Or better, instead of breaking stuff you can *fix* (would you look at that!) the `R` example: `\let\newr=R \catcode`R=13 \def R{I am an A\newr\newr\newr!}`. Quick question: could you rename to `\newR`?
* Finally, the so-called “spurious spaces”. This is kind of a taboo topic because there are people who claim that reputation earned in the [TeX - LaTeX Stack Exchange](https://tex.stackexchange.com) by answering “spurious spaces” questions should not be considered, while others wholeheartedly disagree. Whom do you agree with? Place your bets! Meanwhile: TeX understands a line break as a space. Try to write several words with a line break (not an *empty line*) between them. Now add a `%` at the end of these lines. It's like you were “commenting out” these end-of-line spaces. That's it :)
### (Sort of) ungolfing the code
Let's make that rectangle into something (arguably) easier to follow:
```
{
\let~\catcode
~`A13
\defA#1{~`#113\gdef}
AGG#1{~`#113\global\let}
GFF\else
GHH\fi
AQQ{Q}
AII{\ifxQ}
AEE#1#2#3|{I#3#2#1FE{#1#2}#3|H}
ADD#1#2#3|{I#2FE{#1}#2#3|H}
ACC#1#2|{D{}#2Q|#1 }
ABBH#1 {HI#1FC#1|BH}
\gdef\S#1{\iftrueBH#1 Q }
}
```
### Explanation of each step
each line contains one single instruction. Let's go one by one, dissecting them:
**`{`**  
First we start a group to keep some changes (namely catcode changes) local so that they don't mess up the input text.
**`\let~\catcode`**  
Basically *all* TeX obfuscation codes start with this instruction. By default, both in plain TeX and LaTeX, the `~` character is the one active character which can be made into a macro for further use. And the best tool for weirdifying TeX code are catcode changes, so this is generally the best choice. Now instead of `\catcode`A=13` we can write `~`A13` (the `=` is optional):
**`~`A13`**  
Now the letter `A` is an active character, and we can define it to do something:
**`\defA#1{~`#113\gdef}`**  
`A` is now a macro that takes one argument (which should be another character). First the catcode of the argument is changed to 13 to make it active: `~`#113` (replace the `~` by `\catcode` and add an `=` and you have: `\catcode`#1=13`). Finally it leaves a `\gdef` (global `\def`) in the input stream. In short, `A` makes another character active and start its definition. Let's try it:
**`AGG#1{~`#113\global\let}`**  
`AG` first “activates” `G` and does `\gdef`, which followed by the next `G` starts the definition. The definition of `G` is very similar to that of `A`, except that instead of `\gdef` it does a `\global\let` (there isn't a `\glet` like the `\gdef`). In short, `G` activates a character and makes it be something else. Let's make shortcuts for two commands we'll use later:
**`GFF\else`**  
**`GHH\fi`**  
Now instead of `\else` and `\fi` we can simply use `F` and `H`. Much shorter :)
**`AQQ{Q}`**  
Now we use `A` again to define another macro, `Q`. The above statement basically does (in a less obfuscated language) `\def\Q{\Q}`. This isn't a terribly interesting definition, but it has an interesting feature. Unless you do want to break some code, the only macro that expands to `Q` is `Q` itself, so it acts like a unique marker (it's called a *quark*). You can use the `\ifx` conditional to test if the argument of a macro is such quark with `\ifx Q#1`:
**`AII{\ifxQ}`**  
so you can be pretty sure that you found such a marker. Notice that in this definition I removed the space between `\ifx` and `Q`. Usually this would lead to an error (note that the syntax highlight thinks that `\ifxQ` is one thing), but since now `Q` is catcode 13 it cannot form a control sequence. Be careful, however, not to expand this quark or you'll get stuck in an infinite loop because `Q` expands to `Q` which expands to `Q` which...
Now that the preliminaries are done, we can go to the proper algorithm to pwas eht setterl. Due to TeX's tokenization the algorithm has to be written backwards. This is because at the time you do a definition TeX will tokenize (assign catcodes) to the characters in the definition using the current settings so, for example, if I do:
```
\def\one{E}
\catcode`E=13\def E{1}
\one E
```
the output is `E1`, whereas if I change the order of the definitions:
```
\catcode`E=13\def E{1}
\def\one{E}
\one E
```
the output is `11`. This is because in the first example the `E` in the definition was tokenized as a letter (catcode 11) before the catcode change, so it will always be a letter `E`. In the second example, however, `E` was first made active, and only then `\one` was defined, and now the definition contains the catcode 13 `E` which expands to `1`.
I will, however, overlook this fact and reorder the definitions to have a logical (but not working) order. In the following paragraphs you can assume that the letters `B`, `C`, `D`, and `E` are active.
**`\gdef\S#1{\iftrueBH#1 Q }`**  
(notice there was a small bug in the previous version, it did not contain the final space in the definition above. I only noticed it while writing this. Read on and you'll see why we need that one to properly terminate the macro.)  
First we define the user-level macro, `\S`. This one shouldn't be an active character to have a friendly (?) syntax, so the macro for gwappins eht setterl is `\S`. The macro starts with an always-true conditional `\iftrue` (it will soon be clear why), and then calls the `B` macro followed by `H` (which we defined earlier to be `\fi`) to match the `\iftrue`. Then we leave the argument of the macro `#1` followed by a space and by the quark `Q`. Suppose we use `\S{hello world}`, then the *input stream* should look like this: `\iftrue BHhello world Q␣` (I replaced the last space by a `␣` so that the rendering of the site does not eat it, like I did in the previous version of the code). `\iftrue` is true, so it expands and we are left with `BHhello world Q␣`. TeX does *not* remove the `\fi` (`H`) after the conditional is evaluated, instead it leaves it there until the `\fi` is *actually* expanded. Now the `B` macro is expanded:
**`ABBH#1 {HI#1FC#1|BH}`**  
`B` is a *delimited macro* whose parameter text is `H#1␣`, so the argument is whatever is between `H` and a space. Continuing the example above the input stream prior to the expansion of `B` is `BHhello world Q␣`. `B` is followed by `H`, as it should (otherwise TeX would raise an error), then the next space is between `hello` and `world`, so `#1` is the word `hello`. And here we got to split the input text at the spaces. Yay :D The expansion of `B` removes everything up to the first space from the input stream and replaces by `HI#1FC#1|BH` with `#1` being `hello`: `HIhelloFChello|BHworld Q␣`. Notice that there is a new `BH` later in the input stream, to do a tail recursion of `B` and process later words. After this word is processed `B` processes the next word until the word-to-be-processed is the quark `Q`. The last space after `Q` is needed because the delimited macro `B` *requires* one at the end of the argument. With the previous version (see edit history) the code would misbehave if you used `\S{hello world}abc abc` (the space between the `abc`s would vanish).
OK, back to the input stream: `HIhelloFChello|BHworld Q␣`. First there's the `H` (`\fi`) that completes the initial `\iftrue`. Now we have this (pseudocoded):
```
I
  hello
F
  Chello|B
H
world Q␣
```
The `I...F...H` think is actually a `\ifx Q...\else...\fi` structure. The `\ifx` test checks if the (first token of the) word grabbed is the `Q` quark. If it is there is nothing else to do and the execution terminates, otherwise what remains is: `Chello|BHworld Q␣`. Now `C` is expanded:
**`ACC#1#2|{D#2Q|#1 }`**  
The first argument of `C` is undelimited, so unless braced it will be a single token, The second argument is delimited by `|`, so after the expansion of `C` (with `#1=h` and `#2=ello`) the input stream is: `DelloQ|h BHworld Q␣`. Notice that another `|` is put there, and the `h` of `hello` is put after that. Half the swapping is done; the first letter is at the end. In TeX it is easy to grab the first token of a token list. A simple macro `\def\first#1#2|{#1}` gets the first letter when you use `\first hello|`. The last one is a problem because TeX always grabs the “smallest, possibly empty” token list as argument, so we need a few work-arounds. Next item in the token list is `D`:
**`ADD#1#2|{I#1FE{}#1#2|H}`**  
This `D` macro is one of the work-arounds and it's useful in the sole case where the word has a single letter. Suppose instead of `hello` we had `x`. In this case the input stream would be `DQ|x`, then `D` would expand (with `#1=Q`, and `#2` empty) to: `IQFE{}Q|Hx`. This is similar to the `I...F...H` (`\ifx Q...\else...\fi`) block in `B`, which will see that the argument is the quark and will interrupt the execution leaving only `x` for typesetting. In other cases (returning to the `hello` example), `D` would expand (with `#1=e` and `#2=lloQ`) to: `IeFE{}elloQ|Hh BHworld Q␣`. Again, the `I...F...H` will check for `Q` but will fail and take the `\else` branch: `E{}elloQ|Hh BHworld Q␣`. Now the last piece of this thing, the `E` macro would expand:
**`AEE#1#2#3|{I#3#2#1FE{#1#2}#3|H}`**  
The parameter text here is quite similar to `C` and `D`; the first and second arguments are undelimited, and the last one is delimited by `|`. The input stream looks like this: `E{}elloQ|Hh BHworld Q␣`, then `E` expands (with `#1` empty, `#2=e`, and `#3=lloQ`): `IlloQeFE{e}lloQ|HHh BHworld Q␣`. Another `I...F...H` block checks for the quark (which sees `l` and returns `false`): `E{e}lloQ|HHh BHworld Q␣`. Now `E` expands again (with `#1=e` empty, `#2=l`, and `#3=loQ`): `IloQleFE{el}loQ|HHHh BHworld Q␣`. And again `I...F...H`. The macro does a few more iterations until the `Q` is finally found and the `true` branch is taken: `E{el}loQ|HHHh BHworld Q␣` -> `IoQlelFE{ell}oQ|HHHHh BHworld Q␣` -> `E{ell}oQ|HHHHh BHworld Q␣`-> `IQoellFE{ello}Q|HHHHHh BHworld Q␣`. Now the quark is found and the conditional expands to: `oellHHHHh BHworld Q␣`. Phew.
Oh, wait, what are these? NORMAL LETTERS? Oh, boy! The letters are finally found and TeX writes down `oell`, then a bunch of `H` (`\fi`) are found and expanded (to nothing) leaving the input stream with: `oellh BHworld Q␣`. Now the first word has the first and last letters swapped and what TeX finds next is the other `B` to repeat the whole process for the next word.
**`}`**  
Finally we end the group started back there so that all local assignments are undone. The local assignments are the catcode changes of the letters `A`, `B`, `C`, ... which were made macros so that they return to their normal letter meaning and can be safely used in the text. And that's it. Now the `\S` macro defined back there will trigger the processing of the text as above.
One interesting thing about this code is that it is fully expandable. That is, you can safely use it in moving arguments without worrying that it will explode. You can even use the code to check if the last letter of a word is the same as the second (for whatever reason you would need that) in an `\if` test:
```
\if\S{here} true\else false\fi % prints true (plus junk, which you would need to handle)
\if\S{test} true\else false\fi % prints false
```
Sorry for the (probably far too) wordy explanation. I tried to make it as clear as possible for non TeXies as well :)
### Summary for the impatient
The macro `\S` prepends the input with an active character `B` which grabs lists of tokens delimited by a final space and passes them to `C`. `C` takes the first token in that list and moves it to the end of the token list and expands `D` with what remains. `D` checks if “what remains” is empty, in which case a single-letter word was found, then do nothing; otherwise expands `E`. `E` loops through the token list until it finds the last letter in the word, when it is found it leaves that last letter, followed by the middle of the word, which is then followed by the first letter left at the end of the token stream by `C`.
[Answer]
# JavaScript (ES6), ~~39~~ 36 bytes
*Saved 3 bytes thanks to @FryAmTheEggman*
Uses a linefeed as separator.
```
s=>s.replace(/(.)(.*)(.)/g,'$3$2$1')
```
[Try it online!](https://tio.run/##TVDRasQgEHy@@4olHERLm9D2OfclfVnMxuQwKq5tuPv5dA3JcYKgszPjjDf8QzZpivnDh57WoVu5u3KTKDo0pFrVaNW8ydatfa8v35evy2et10ycoQOG7gomeA6OGhesGhQ3HN2UVQ21bm5h8qr@8bXWB1wuOy4MfT4XK1XxghHySDBMSazR9@BQDo5ypsQQBiA0Iywh9ZU@tS1UcUEGGjNkkQzQe4SM7IA3iYMhwCgdoA9pqfZnRnIuFBMnLnAqq1gFgcdCdE/m1tAgE78SN5QFNQcvpmATzvPkLcTfx8MRb@mNfCfY4IZNXrT2yYzAGzNuoSn0RsI6e1hOHhBsIvIwE/ZhkcKwB/CTzLzMLCxlNh@iO94hSV2DSehH3ld0/Qc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~8~~ 5 bytes
```
,V,,`
```
[Try it online!](https://tio.run/##DcZBCsAgDATA@74ll36m54a6oiAqScDnp53TGKNPvTLlFnky/ehGNKJ284DOgqF/BiNojlVBfRvOsvIB "Retina – Try It Online")
Saved 3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
Uses a newline as the separator. We make use of Retina's reverse stage and some limits. The first limit is which matches to apply the reversal to, so we pick all of them with `,`. Then we want the first and last letter of each match to be swapped, so we take each letter in the range `,,` which translates to a range from the beginning to the end with step size zero.
[Answer]
# [Pepe](https://github.com/Soaku/Pepe), ~~107~~ 105 bytes
```
REEeREeeEeeeeerEEreREEEeREEEEEEeREEEErEEREEEEEEEreererEEEeererEEEerEEeERrEEEeerEEeerereeerEEEEeEEEReEeree
```
[Try it online!](https://soaku.github.io/Pepe/#T!8hE$!pE5!rEE7*$-c$!o!m--c!k$GRyL*)
**Explanation:**
Notation on comments: `command-explanation -> (stack) // explanation`
```
REEe # input -> (R)
REeeEeeeee # push space to last -> (R) // this prevents an infinite loop
rEE # create loop labeled 0 and automatically push 0 
  re # pop 0 -> (r)
  REEEe # go to last item -> (R)
  REEEEEEe # ...then copy the char to other stack
  REEEE # go to first item -> (R)
  rEE # create loop labeled 32 // detect space
    REEEEEEE # move item to other stack (R)
  ree # do this while char != 32
  re # pop 32 -> (r)
  rEEEee # push item (dup to end) -> (r)
  re # ...then pop -> (r)
  rEEEe rEEeE # go to 2nd to last item -> (r)
  RrEEEee # push the item (R flag: dup to first) -> (r)
  rEEee # go to next -> (r) //
  re # ...then pop -> (r)
  reee rEEEEeEEE # out all as char then clear -> (r)
  ReEe # out 32 as char -> (R)
ree # do this while stack != 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~72~~ 58 bytes
```
print(*[x[-1]+x[1:-1]+x[:x>x[0]]for x in input().split()])
```
[Try it online!](https://tio.run/##JcZBCsMgEEbhq/zLpKWhobssehFxIYmiIDqMEzI5vRUKD75Ht8RaPr0TpyLTw6h5rfapZt3@bvpV87Y2VIYilRGdMs1Lo5yGdu69XY4g0SMkbgJXDmQ3JnsRzw01wLs94qp8/AA "Python 3 – Try It Online")
[Answer]
# [laskelH](https://www.haskell.org/), 71 bytes
```
h=reverse
s(x:y:o)=a:h(x:r)where(a:r)=h$y:o
s o=o
f=unwords.map s.words
```
[Try it online!](https://tio.run/##ZVJBbhsxDLzrFTwEaAI0foCBfYCBopfmA8yattjViguRymb7eZeS10DQnkRR5HA4o4g6UUq3WxwKfVBRCvr8edyO8jLgMXpYXtZIhZ7RoyE@@UtQkEHCZah5lXLWw4wL6KHHt9dXOH2bIYvBKDUb5ytYZAVUWLAYyMXvBDwviWbKhsaSQfkPhRk5wwCcjQqOBk9Qc@JMCgdoMy5@9vvt1@rXBnPhogaYz5DQg0TmvY4AhGOERim89elJpV0nhZUt@rx8TfSo79QdeiLAEE4G3vGOyiOmtMHv2kaAWkG@RoO6/Mve562RxxhOcJEH3ChZWbsAbedVwJ9mKY@p94q@RSQ8h12Y3YYzGHICB/@SfIgnha@cMfXGDkPen//vD@GnGHke7f5Yk6upuN1Tq0Nl3zDihxcJaF0WaR5lgolz56TktqE5d3cWcIYxijT5QBccHe2Nxph3qdi@iBzER5amjFGvbX9g9d/2Hd6r9VpOCawWt8tJb/5PHNbtlx078H0ncn9/uPEt8BKFnneT6BObE1AVrw7v2kb/C8m332lT2oLDzTjRHWlvkGqLc0giEzh5Kn8B "Haskell – Try It Online")
Example in/output:
```
Swap the first and last letter in each word
This also works with single letter words like a
It is basically just a straight up implementation in which
I for words consisting of two or more letters cons the head
of the reversed tail on the reverse of the original head consed
on the reversed tail
Note that the rules say that we only have to support one kind
of separator - I am choosing spaces Technically it works with
other whitespace as well, but it will turn everything into spaces
in the end Line endings in this example usage are handled separately
to make the example output look nicer
```
```
pwaS eht tirsf dna tasl rettel ni hace dorw
shiT olsa sorkw hitw eingls rettel sordw eikl a
tI si yasicallb tusj a ttraighs pu nmplementatioi ni hhicw
I rof sordw gonsistinc fo owt ro eorm setterl sonc eht deah
fo eht deverser lait no eht eeversr fo eht lriginao deah donsec
no eht deverser lait
eotN that eht suler yas that ew ynlo eavh ot tuppors eno dink
fo reparatos - I ma ghoosinc spaces yechnicallT ti sorkw hitw
rtheo ehitespacw sa ,ellw tub ti lilw nurt gverythine onti spaces
ni eht dne einL sndinge ni shit example esagu era dandleh yeparatels
ot eakm eht example tutpuo kool ricen
```
```
[Answer]
# [J](http://jsoftware.com/), ~~23~~ 17 bytes
```
({:,1|.}:)&.>&.;:
```
[Try it online!](https://tio.run/##TY1BDoIwFET3nmJWVhLS4LZG7/LT/gKm8ElbQ0A5O6ILcTd5My9zX51A@atWJRZTwVTr6WnK80svpjjq21FfzFoc2DYCD5VGGpAbhm9jyqDeIdAWAufMMUE8mGyDUaJTP6vhEOTDwh/MvHmWEqedDVHqSF3X9jWGxzwHTt8PK45RS/D7tO1BqCNzj47JybhXE02IZNlSVOsb "J – Try It Online")
[Answer]
# x86-16 machine code, IBM PC DOS, ~~39~~ ~~38~~ 32 bytes
```
$ xxd pwas.com
00000000: d1ee ac8a c8ac 8bd6 8bfe f2ae 574f 4f8a  ............WOO.
00000010: 25a4 4e88 245e 41e2 efb8 2409 aacd 21c3  %.N.$^A...$...!.
```
Unassembled:
```
D1 EE       SHR  SI, 1              ; DOS PSP (80H) for command line input 
AC          LODSB                   ; get input length, SI at beginning 
8A C8       MOV  CL, AL             ; input length in CX 
AC          LODSB                   ; load a space (word delimiter) into AL 
8B D6       MOV  DX, SI             ; save pointer for later output 
        WORD_LOOP: 
8B FE       MOV  DI, SI             ; start DI at beginning 
F2 AE       REPNZ SCASB             ; search for next word delimiter 
57          PUSH DI                 ; save beginning of next word 
4F          DEC  DI                 ; DI will now point to the byte after the space 
4F          DEC  DI                 ;  so it's necessary to back up two chars 
8A 25       MOV  AH, BYTE PTR[DI]   ; move last letter to AH 
A4          MOVSB                   ; move first letter to last position 
4E          DEC  SI                 ; offset MOVSB incrementing SI 
88 24       MOV  BYTE PTR[SI], AH   ; move last letter to first position 
5E          POP  SI                 ; SI to beginning of next word 
41          INC  CX                 ; offset LOOP decrementing CX 
E2 EF       LOOP WORD_LOOP          ; loop if not end of input string 
B8 0924     MOV  AX, 0924H          ; AH = 9, AL = '$' 
AA          STOSB                   ; write DOS string delimiter to end 
CD 21       INT  21H                ; write to console 
C3          RET                     ; return to DOS
```
Standalone PC DOS executable. Input via command line, output to console.
[![enter image description here](https://i.stack.imgur.com/fxyWa.png)](https://i.stack.imgur.com/fxyWa.png)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
#vyRćsRćðJ
```
[Try it online!](https://tio.run/##LYrBCYAwEARbWbAbn3ZwmlMPj0RyMWIFtmMP2lcM6GOZgdlg1AuX0uSje06ru6@2FNtpRZoZo0RLIO@gVEU5JY6GMIJpmLGH6CB@0M2Jn0CwCuX/92WVhWsJEQKjnI8X "05AB1E – Try It Online")
---
-3 Thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
```
#           | Split into words.
 vy         | For each word...
   RćsRć    | Reverse, split head, swap, reverse, split tail
        ðJ  | Join by spaces.
```
[Answer]
## Haskell, 54 bytes
```
unwords.map f.words
f[a]=[a]
f(a:b)=last b:init b++[a]
```
[Try it online!](https://tio.run/##LU5LrsIwDNz3FKOuQDx6AKTegLd6S0DIpE4avfyUpKrg8IS0ZWHZM/aMZ6T0z8YU1V/L5GYfh9RZCpDdOjfyQre@ViN3dHrse0Mp43HSTtd2ONRNsaQdelTV7x27MOW/HM8Ondrj0gBtmqtfHhlSxyomN2B1MZwzxwQvwSRGLA/bn0Ux1kR@weZLZK73ghKnDYfoVSRrtVMI0@tlOK2@wg8M5Y3czmougorMDpZp8PNGP@mJSIIFxfbWlLeQhlQqRxHCBw "Haskell – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 37 bytes
```
$args-replace'(\w)(\w*)(\w)','$3$2$1'
```
[Try it online!](https://tio.run/##TU/dasMgGL3PUxyCW5ORXmy7GxT2IIMh@sUETHRqcW3XZ88@k65MUDx/fkfvMoU4kLWL6A@XRchg4j6Qt1LRrvnILe@ncrS7bidexYt43i3Xqnpvqq6pY5YeaSD0Y4gJctawki@WUuJ34XqQVAOyC7ruap9lBA0Jie099CyRZLSIq92idxh4LrQLuW7LgNLMlbjlPGrHcCiyvemJeJqSkWKRVxQZqU31wZkgp2mcDfzxfLYU147KaYJxti8hczd5xNXk12bktOJG1mxvjTMkTCCaMZHULpfsPDI5M2mQCzlt3pM8IfBHlAzF9R@2VYsfPOBSgZeIHQR9e1KJNA4QnxsdKB5tYuJR9GxayVo0N36v6Oueat/@7HV1XX4B "PowerShell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) with `-p`, ~~42~~ ~~41~~ 29 bytes
```
gsub /(\w)(\w*)(\w)/,'\3\2\1'
```
[Try it online!](https://tio.run/##HYxBDoMwDATveYVvlKoVavudXExiQqQQR3YQgsc3hR5mNYfVyDrurQVdRxhudutP7tf0w6OzH/u2r6413bBAnQmmKFoBs4eEpySqlUSBJyB0M2ws3syUEl@avKl0vhwqqSnCQXBZYg5Q1uNIpP@QY08QOE0mZkAIQpRhIfS8mR13EHTkUL5cauSs7Vl@ "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 7 bytes
```
¸®ÎiZÅé
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=uK7OaVrF6Q&input=InN3YXAgdGhlIGZpcnN0IGFuZCBsYXN0IGxldHRlcnMgb2YgZWFjaCB3b3JkIg)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
⌈ƛḣǔp;Ṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIjGm+G4o8eUcDvhuYQiLCIiLCJTd2FwIHRoZSBmaXJzdCBhbmQgbGFzdCBsZXR0ZXJzIG9mIGVhY2ggd29yZCJd)
```
⌈     Ṅ # To the words split on spaces...
 ƛ   ;  # Over each
  ḣ     # Take the first character and the rest
   ǔ    # Rotate the rest
    p   # Append the first char
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Σq╞♪áZN¢
```
[Run and debug it](https://staxlang.xyz/#p=e471c60da05a4e9b&i=swap%0Athe%0Afirst%0Aand%0Alast%0Aletters%0Aof%0Aeach%0Aword%0A%0Ahello%0Aworld%0A%0Atest%0Acases%0A%0Aprogramming%0Apuzzles%0Aand%0Acode%0Agolf%0A%0Ain%0Aa%0Agreen%0Ameadow%0A%0Ayay%0Aracecar%0A&a=1&m=1)
Uses newlines as word separators.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 179 bytes
```
[N
S S S N
_Create_Label_OUTER_LOOP][S S S N
_Push_n=0][N
S S T   N
_Create_Label_INNER_LOOP][S N
S _Duplicate_n][S N
S _Duplicate_n][S N
S _Duplicate_n][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S S S T    S T T   N
_Push_11][T S S T   _Subtract_t=input-11][N
T   T   S S N
_If_t<0_jump_to_Label_PRINT][S S S T    N
_Push_1][T  S S S _Add_n=n+1][N
S N
T   N
_Jump_to_Label_INNER_LOOP][N
S S S S N
_Create_Label_PRINT][S S S T    N
_Push_1][T  S S T   _Subtract_n=n-1][S N
S _Duplicate_n][S N
S _Duplicate_n][N
T   S N
_If_n==0_jump_to_Label_PRINT_TRAILING][T    T   T   _Retrieve][T    N
S S _Print_as_character][S S S N
_Push_s=0][N
S S S T N
_Create_Label_PRINT_LOOP][S S S T   N
_Push_1][T  S S S _Add_s=s+1][S N
S _Duplicate_s][S T S S T   S N
_Copy_0-based_2nd_n][T  S S T   _Subtract_i=s-n][N
T   S N
_If_0_Jump_to_Label_PRINT_TRAILING][S N
S _Duplicate_s][T   T   T   _Retrieve][T    N
S S _Print_as_character][N
S T S T N
_Jump_to_Label_PRINT_LOOP][N
S S N
_Create_Label_PRINT_TRAILING][S S S N
_Push_0][T  T   T   _Retrieve][T    N
S S _Print_as_character][S S S T    S S T   N
_Push_9_tab][T  N
S S _Print_as_character][N
S N
S N
_Jump_to_Label_OUTER_LOOP]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.  
`[..._some_action]` added as explanation only.
Tab as delimiter. Input should contain a trailing newline (or tab), otherwise the program doesn't know when to stop, since taking input in Whitespace can only be done one character at a time.
[Try it online](https://tio.run/##TY7hDoMgDIR/X5@ir9ZonWREDTDNnp61lsQlQK/0u4NrTU3rIZP2Tsx8bztALu8FAgOwgVdr/AaB3q0pgpv@7hBek8aai3kEMx6fM8FGqBt44OSvEY0fPRlBRjhT7/WSA21VLKnUBtlmZDGRtTUtFfsClWnFtZcZaZvyZ07bC4JqJevgYpzTW22yFyRUOc8v/QA) (with raw spaces, tabs, and new-lines only).
**Explanation in pseudo-code:**
Whitespace only has a stack and a heap, where the heap is a map with a key and value (both integers). Inputs can only be read one integer or character at a time, which are always placed in the heap as integers, and can then be received and pushed to the stack with their defined heap-addresses (map-keys). In my approach I store the entire word at the heap-addresses (map-keys) \$[0, ..., \text{word\_length}]\$, and then retrieve the characters to print one by one in the order we'd want after a tab (or newline) is encountered as delimiter.
```
Start OUTER_LOOP:
  Integer n = 0
  Start INNER_LOOP:
    Character c = STDIN as character, saved at heap-address n
    If(c == '\t' OR c == '\n'):
      Jump to PRINT
    n = n + 1
    Go to next iteration of INNER_LOOP
  PRINT:
    n = n - 1
    If(n == 0): (this means it was a single-letter word)
      Jump to PRINT_TRAILING
    Character c = get character from heap-address n
    Print c as character
    Integer s = 0
    Start PRINT_LOOP:
      s = s + 1
      If(s - n == 0):
        Jump to PRINT_TRAILING
      Character c = get character from heap-address s
      Print c as character
      Go to next iteration of PRINT_LOOP
    PRINT_TRAILING:
      Character c = get character from heap-address 0
      Print c as character
      Print '\t'
      Go to next iteration of OUTER_LOOP
```
The program terminates with an error when it tries to read a character when none is given in TIO (or it hangs waiting for an input in some Whitespace compilers like [vii5ard](http://vii5ard.github.io/whitespace/)).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 58 bytes
```
StringReplace[#,a:u~~w:u..~~b:u:>b<>w<>a/.{u->Except@#2}]&
```
[Try it online!](https://tio.run/##TY89a8MwEIb3/IrDgkyOCx1NKrRkL@0YMlzkk22QLKEP1MTYf91V28Hdjufu4b3XYBzIYBwlbupt@4x@nPoPcholXVmNbVrX3KamWdd7m1p@P/N85vjSzOnEL1@SXBTsdbkdt/dixuvM2HLiSjB2Owoh5sNchYwOSgqo0YcIOHWgsQyaYiQfwCoglANk67uqrqBa6mINpLX9YfofjFQ8iYHCzpy3vUdjyt/g0vOpKfxmSNsR9Far/XScAKH3RBMYws7mffXAB/jSWaL/g4dl@wY "Wolfram Language (Mathematica) – Try It Online")
*-22 bytes from @attinat* 
*-12 bytes from @M.Stern*
[Answer]
# Ruby, 53 bytes
```
gets.split(" ").map{|z|print z[-1]+z[1..-2]+z[0]," "}
```
I tried it without regex. The output prints each word on a new line. If that's against the rules, let me know and I'll fix it.
Ungolfed:
```
gets.split(" ").map {|z|
    print z[-1] + z[1..-2] + z[0], " "
}
```
[Answer]
# [Zsh](https://zsh.sourceforge.io/), 36 bytes
```
for x;<<<$x[-1]${x:1:-1}$x[1]||<<<$x
```
[Try it Online!](https://tio.run/##HYyxjoMwEER7f8UUSMkVKWgDiu4/jhR7Zo2RjM2tHUEIfDtnaFb7Zp5miXaPE43Xr89ugmCu6rou5p9b@Sw@872838otY/lc17PYN2Wyq4BRep8MLg9cqmMBxfeaBE3j0aBibYPalDI4u2QZppeYQL6Fo/w4ToklIhgwaYspSJt1y86FA9xBibOpKXLMMErohIah9x3G17I4juecDi2jC85kp/cgdMLsMTC1YcrZm94Q0qxJMtFvPn/7Pw)
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 20 bytes
```
(\w)(\w*)(\w)
\3\2\1
```
Simply make three capturing groups consisting of 1, 0-or-more, and 1 word-characters, then reverses their order.
[Try it online!](https://tio.run/##TY/BbsMgEETv@YqRT0mlHpre@yW@rGABS2ugLBFKft5d21XVA4idmQfD94N827brPG623vbtdpk/5/v8sW2TDqroiRGWph2UPYTsINw7N0UJYHIJozQ/4f0LUx2k4NTRjQjwmdBJBXoQglCQyDF8aWO6TIlFyo7LL19MSLsru93ZHnOkrKd7zGqzM7O2Ehut65Ij6uP1EtajoSueEYuEk4l/sQo9YvWoxcU7qyPRrloyCLExZ6xMvowTzYvJ2eSIscurRZ/0RLMfOGpn6L/wAw "QuadR – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 24 bytes
```
s/(\w)(\w*)(\w)/$3$2$1/g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YXyOmXBOItUCEpr6KsYqRiqF@@v//Gak5OfkK5flFOSn/8gtKMvPziv/r@prqGRgZ/dctAAA "Perl 5 – Try It Online")
[Answer]
## Batch, 141 bytes
```
@set t=
@for %%w in (%*)do @call:c %%w
@echo%t%
@exit/b
:c
@set s=%1
@if not %s%==%s:~,1% set s=%s:~-1%%s:~1,-1%%s:~,1%
@set t=%t% %s%
```
Takes input as command-line parameters. String manipulation is dire in Batch at best, and having to special-case single-letter words doesn't help.
[Answer]
# APL+WIN, 50 bytes
```
(∊¯1↑¨s),¨1↓¨(¯1↓¨s),¨↑¨s←((+\s=' ')⊂s←' ',⎕)~¨' '
```
Prompts for string and uses space as the delimiter.
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5rPOroOrTe8FHbxEMrijV1Dq0AMicfWqEBFpsMFYPIAjVpaGjHFNuqK6hrPupqAgkAmTpAEzXrDq0AMv8DjfyfxqVeXJ5YoFCSkaqQlllUXKKQmJeiALS9RCEntaQktahYIT9NITUxOUOhPL8oRR0A "APL (Dyalog Classic) – Try It Online")
[Answer]
## sed, 64 bytes
```
sed -E 's/\b([[:alpha:]])([[:alpha:]]*)([[:alpha:]])\b/\3\2\1/g'
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), 34 bytes
And presumably the pattern idea will work with most RE tools (and I do know there are differences between standard RE and extended RE).
```
s,\b\(\w\)\(\w*\)\(\w\)\b,\3\2\1,g
```
[Try it online!](https://tio.run/##NY89TsUwEIT7nGJKQHnFg1MgISpKN5tkia04Xss/L@T0YeNAM2uNZz@PM0@3OdTjyL0ZzJPZzPOpL9dQHXrzZl7NvZ@P41MKo1gqKoxUPWdk2i9rY0jwOyw9NCTINUZJRU3G4sLUyTcyR0pUJOGGd9CK0YpkF2bkSKPSvni0wY3kFeSUKWnJ2FyxneiTCZt1hVsWpBfsfY@hlpZ13qPUFMAPTnuxJ9aFs0ljdy602hwmfLjQDhrJaL7L4B9ao2fUTLPiE@tXwuR5@q/Nfu8Ut9LCF@lvQWqJ2sGLLNDynLpf "sed – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 75 bytes
```
x->join([(n=length(s);n<2 ? s : s[n]*s[2:n-1]*s[1]) for s in split(x)]," ")
```
[Try it online!](https://tio.run/##VY7LDoIwFET3fsWEVWtkAUvf/0FYVLiFmuaW9FbBr8e6UneTMzmZuT@8M9Wy2tONBsfrUp7vwbFqFJ888ZBGJfrAxxoXCPaQhtutNPWey@oTqlbDhpg7x5DJu6QW3e4KFHol7jdXGcMMqwqZzYQ0EqyLkmC4hzc5eEqJIoIFPSm@MIfYF/rrjeR9@FD/hxNltzNC8ksNbujQI69gyA/e "Julia 1.0 – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 110 bytes
```
|a:&str|{for b in a.split(' '){let l=b.len()-1;if l>0{print!("{}{}",&b[l..],&b[1..l])}print!("{} ",&b[0..1])}}
```
[Try it online!](https://tio.run/##RU@9DoMgEN59iiuDQtISXWvsM3RvHLCiITnBAKaJyLNbdGhv@ZL7/u7s4vw@aJiE0pRByCANSg8Omn0T99x5u4XBWOhAaRDczag8LaBg4ZBh03GUyXqrajUAPsowW6X9hZIQQyTXvHsh5@2BFefYsvjn4aRLzqu0jnt9ljtKntaMVkyT0iPMy7qidCB0D2/TSxgNDoTVZwrqC2U/23EfjFbK9I4UvfkkWRb3Lw "Rust – Try It Online")
### A surprisingly long, but nicer solution that returns instead of printing (126 bytes):
```
|a:&str|->String{a.split(' ').flat_map(|b|{let mut q:Vec<_>=b.chars().collect();q.swap(0,b.len()-1);q.push(' ');q}).collect()}
```
[Try it online!](https://tio.run/##dY@9jsIwEIT7e4q9FGBLYB0tOXiGk5Bo0cZxQqT1T@yNkEjy7MGkuoYpR9/szMYh8dI4sNg5IWH8giwyDAlOy4THTeI47c8Xjp1rR1QpUMdiC1upGkK@WQxiqqbxHbEDQ3@8Gv17O58qpe8Yk5BKeyKjWciyV@mR@Z9dpcjkuv3h7YUh3deLZT//o@elXMeE3MzkvkUxzsUOkij@om8jWpsXQRieTzIJ0NWgfW2g9dQUUn7Kdg4Q2mhMftlg7R8rOy8v "Rust – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes
```
aR+XW{@a::a@va}
```
Takes the string as a command-line argument. [Try it here!](https://replit.com/@dloscutoff/pip) Or, here's a **14-byte** version in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/MUg7Irw62CEx0aEssfb////F5YkFCiUZqQppmUXFJQqJeSkKOYlARk5qSUlqUbFCfppCokJ5flEKAA "Pip – Try It Online")
### Explanation
```
aR+XW{@a::a@va}
a                In the command-line argument,
 R               replace all matches of
  +XW            the regex `\w+`
     {        }  with the following callback function:
      @a          Take the first character of the matched string
          a@v     and its -1th (last) character
        ::        and swap them
             a    Return the modified string
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
wm§:→oṙ1hw
```
[Try it online!](https://tio.run/##yygtzv7/vzz30HKrR22T8h/unGmYUf7////i8sQChZKMVIW0zKLiEoXEvBSFnEQgIye1pCS1qFghP00hNTE5Q6E8vygFAA "Husk – Try It Online")
### Explanation
```
wm§:→oṙ1hw
 m       w  map over each word
  §:        concatenate the
    →       last char
     o  h   and the rest
      ṙ1    rotated
w           join on spaces
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 5 bytes (10 nibbles)
```
:`(\@:`)\$
```
Word separator is newline character.
```
:`(\@:`)\$$ # (code with implicitly-added final $)
            # implicit map over lines of input:
:           # joined
 `(         # first character of
   \@       # reversed word
            # (and save leftover of reversed word in variable $)
            # with
     :      # joined
      `)    # all but first character of
        \$  # reversed leftover of reversed word
            # with
          $ # first character of leftover of reversed word
            # (so, first character of the original word)            
```
[![enter image description here](https://i.stack.imgur.com/tNC2d.png)](https://i.stack.imgur.com/tNC2d.png)
]