Created
December 3, 2022 21:37
-
-
Save AshyIsMe/12449fb69ad23b5d74d8989b293fe09d to your computer and use it in GitHub Desktop.
forks and hooks in j
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NB. What the hell is a fork, a hook and cap? | |
NB. a is a simple array | |
a =: 1 2 3 4 5 6 7 8 9 10 | |
NB. What is the average of a? | |
NB. sum divided-by count | |
(+/ a) % (# a) | |
5.5 | |
NB. It was a bit inconvenient to have to repeat a twice and use the parenthesis though. | |
NB. So J has a shorthand syntax to make this more convenient: | |
NB. The fork: | |
(f g h) y | |
NB. Is parsed and executed the same as: | |
(f y) g (h y) | |
NB. Or if we had two arguments: | |
x (f g h) y | |
NB. equivalent to: | |
(x f y) g (x h y) | |
NB. So back to our average example: | |
(+/ % #) a | |
5.5 | |
NB. Nice, Now we're code golfing! | |
NB. contrived example: | |
NB. What if we actually want to find out what half of the average is? | |
-: 5.5 | |
2.75 | |
(-: +/ % #) a | |
0 | |
NB. wat. That's not right. | |
NB. J also has another syntax shorthand called a hook: | |
NB. The hook: | |
(f g) y | |
NB. Is parsed and executed the same as: | |
y f (g y) | |
NB. Or with 2 arguments: | |
x (f g) y | |
NB. equivalent to: | |
x f (g y) | |
NB. In practise the hook seems to be less useful than the fork I think... | |
NB. So what went wrong with this? | |
(-: +/ % #) a | |
NB. A definition like this is called a verb train, and it gets parsed into | |
NB. a series of forks where the last one is either a fork or a hook depending on | |
NB. if the train had enough verbs or not. | |
(-: +/ % #) a | |
NB. (u (f g h)) a | |
NB. (u ( v )) a <-- oh crap, we accidentally made a hook! | |
NB. which gets parsed as: | |
a -: ((+/ % #) a) | |
NB. So how we do stop this verb train from being a hook at the end? | |
NB. The cap! [: | |
([: -: +/ % #) a | |
2.75 | |
NB. Correct! | |
NB. The cap is a placeholder verb so that the train gets parsed as a fork. | |
NB. Cap doesn't actually get executed or return anything. | |
([: g h) y | |
NB. Is equivalent to: | |
g (h y) | |
NB. It's a bit ugly at first, then you get used to it and it's still a bit ugly but usable at least. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment