Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
ac123511477yLet's just start with the broad picture:
We have two little functions: neigh and life.
'neigh' receives a matrix (list of lists) of bools, 0 for dead cell and 1 for living cell respectively. It returns an integer matrix, where each cell is now represented by the number of neighbors (0-8).
'life' is where the magic happens: we receive a bool matrix, a generation of game of life, and return the next generation, also as a bool matrix.
> life:{(x&2=neigh x)|3=neigh x}
The rules are simple: A cell with 3 neighbors will live on (3=neigh x).
If a cell is already alive (x) and (&) has 2 neighbors (2=neigh x) it will also survive.
'x' is our bool matrix we get as an argument. K conveniently allows us to not name our argument explicitly, but we could have called it 'board' or 'grid' or something.
If you want to, I can also explain 'neigh'.
Feel free to ask a question :) -
ac123511477y@bioDan The "magic" is that K loops for us.
Instead of writing "for row in x: for cell in row: ..." we can just use "x" in an element context and K does the looping for us.
This is basically the main property distinguishing APL, K, ... from other languages.
For example, list of 5 numebers:
> !5
0 1 2 3 4
Now we want to add 1 to each, but since K does the for-eachy stuff for us, we can just write:
> 1+ !5
1 2 3 4 5 -
bioDan61597y@ac1235 thanks! Although except from shorter syntax, i can't see the advantage from lets say (in Ruby which in return has better readability):
(0...5).each { |num| num + 1} -
ac123511477y@bioDan It might be more readable to implement 1+each in Ruby, but writing game of life in it will take you longer.
It is not about short code, it's about a short thought process: I can write something like this in seconds and APLers do have an easy time reading it.
The main advantage IMO is composability: since we don't use loops or recursion in K, we basically create a bunch of reusable functions without writing closed systems like loops or recursive functions or alike.
This allows for very high code reusability and, in turn, less work.
Related Rants
Today's achievement: wrote game of life in K3.
neigh:{(+/,/-1 0 1!'\:/:-1 0 1!\:x)-x}
life:{(x*2=neigh x)|3=neigh x}
undefined
k
apl
arrayprogramming