jdan / j

Some code examples for the J programming language
5 stars 1 forks source link

Numeronyms #5

Open jdan opened 6 years ago

jdan commented 6 years ago

Numeronyms

[How to read this blog post]

Special thanks to Tracy Harms for first showing me this code in a talk of his, which finally made "forks" click!

NB. A numeronym is formed by joining:
NB. - The first letter of the string
NB. - The number of letters between the ends of the string (length - 2)
NB. - The last letter of the string

NB. So "numeronym" itself is transformed as follows:
NB. n [umerony] m
NB.     ^^7^^
NB. n7m

NB. We can grab the first letter of the string
{. 'internationalization'
NB. i

NB. We can grab the last letter of the string
{: 'internationalization'
NB. n

NB. We can grab the number of letters in the string
# 'internationalization'
NB. 20

NB. We can partially evaluate a verb with using "binding"
2 + 3
NB. 5
(2&+) 3
NB. 5

5 - 1
NB. 4
(-&1) 5
NB. 4

NB. We can create a verb that subtracts 2 from an input
(-&2) 10
NB. 8

NB. We can compose verbs
# 'hello'
NB. 5
((-&2) @ #) 'hello'
NB. 3
((-&2) @ #) 'internationalization'
NB. 18

NB. We can concatenate lists
1 2 , 3 4
NB. 1 2 3 4
'hello ' , 'world'
NB. hello world

NB. But we can't mix types
1 2 , 'hello'
NB. |domain error
NB. |   1 2    ,'hello'

NB. The format verb can convert numbers to strings
(": 1 2) , 'hello'
NB. 1 2hello

NB. We can compose our length-minus-2 further
((-&2) @ #) 'internationalization'
NB. 18
(": @ (-&2) @ #) 'internationalization'
NB. 18 (but a string!)

NB. We can begin building our numeronym verb
({. 'numeronym') , ((": @ (-&2) @ #) 'numeronym') , ({: 'numeronym')
NB. n7m

NB. J allows us to transform (f x) g (h x) into (f g h) x
({. 'numeronym') , (((": @ (-&2) @ #) , {:) 'numeronym')
NB. n7m

NB. We can keep going
({. , (": @ (-&2) @ #) , {:) 'numeronym'
NB. n7m

NB. We can save this as our own verb
n7m =: {. , (": @ (-&2) @ #) , {:
n7m 'internationalization'
NB. i18n

n7m 'accessibility'
NB. a11y