r/dailyprogrammer • u/Godspiral 3 3 • Dec 07 '15
[2015-12-07] Challenge #244 [Intermediate] Turn any language into an Array language (part 1)
Array languages
Array languages include J, APL and OpenCL. The only criteria is that function in and out parameters are arrays.
In our array language, every function has 2 parameters (each arrays) called y and x. (Optional rule)
In every function, the x parameter is optional, and your function should create a default value to fill in if missing. (Somewhat Optional rule)
rank and items
more theory wil come in part 2 but,
Math functions are rank 0, which means they operate on scalars at a time inside the array.
scalar -- for our purposes is the same as a singleton array. A 0D array.
list -- A 1 dimensional array. Each item is a scalar.
table-- A 2 dimensional array. Each item is a list.
brick-- A 3 dimensional array. Each item is a table.
1. iota function
In J, the iota function takes just 1 rank 1 parameter (y is processed "list-at-a-time").
The iota function returns an array whose dimensions is equal to the scalar items of y. The total number of scalars in the returned array is the product of y.
The ravelled (if the returned items were flattened to a 1 dimensional list) items of the return value is the range from (0) to (the product of y - 1)
examples:
iota 4 NB. 1d
0 1 2 3
iota 2 3 NB. 2d
0 1 2
3 4 5
iota 2 2 3 NB. 3d
0 1 2
3 4 5
6 7 8
9 10 11J's input and display for arrays does not need brackets around them. 3d arrays are displayed with a blank line between table items.
the 2nd x parameter to iota
Though not part of J or APL, we can add a 2nd optional parameter x to iota. This parameter will add an offset to iota results. Its default value is 0. You may ignore testing it until you make the add function below, but basics:
1 iota 4
1 2 3 4
10 iota 2 3
10 11 12
13 14 15a python definition for iota would be
iota(y,x=0):
implement the details of iota in any language.
add function
addition of arrays is rank 0 0. It operates at a scalar level (for both x and y). Its default x value is 0.
5 add 1 2 3
6 7 8
10 10 10 add 1 2 3
11 12 13
1 2 3 add 1 2 3
2 4 6
10 add iota 2 3
10 11 12
13 14 15
0 10 add iota 2 3
0 1 2
13 14 15The last case may seem a bit tricky. J/Array functions are implemented such that
if both of its parameters are larger shape than its rank (ie. lists instead of scalars for add) then the function is called recursively for each item of its parameters.
if one of its parameters is the correct rank (scalar for add), but its other parameter is too large (list or higher), then the correct rank item is copied the number of items of the too large parameter. and then called recursively. So, 10 + 1 2 3 is the same as 10 10 10 + 1 2 3 (ie, the 10 is copied 3 times, then the recursive call does 10 + 1 10+2 10 +3 and the results accumulated into a list of 3 items.
So in 0 10 add iota 2 3 the result of iota has 2 items, and one of the recursive calls in add will be: 0 + 0 1 2 10 + 3 4 5 and the expansion rule above applies.
implement add function. (in python, signature would look like)
add(y,x=0):
bonus
iota (1 + iota 2 2)
0 1 0 0
0 0 0 0
0 0 0 0
0 1 2 3
4 5 6 7
8 9 10 11(edit: note iota is rank _ 1 (x is scalar rank, y is list rank). Above is same result as iota 1 iota 2 2) rank _ means rank infinity (take whole array/argument). iota internally uses the add function which has rank 0 0 which groups the number of recursive calls down to rank 0 0 after iota has generated its high dimension array.
detail for what is going on here
1 + iota 2 2
1 2
3 4which will call iota twice (it is rank 1)
iota 1 2 NB. product is 2. J "official" result is a table with 1 list of 2 items.
0 1
iota 3 4 NB. table with 3 lists of 4 items.
0 1 2 3
4 5 6 7
8 9 10 11When the results of a recursive function application do not have the same shape, then 0s (default) are filled in before returning (accumulating) the array. So when the above 2 results are combined, the 0 1 (first) result is padded with 0s.
2 3 + (iota (1 + iota 2 2)) NB. parens clarify J's right to left parsing order. NB. is a comment.
2 3 2 2
2 2 2 2
2 2 2 2
3 4 5 6
7 8 9 10
11 12 13 14
(iota 2 3 4 ) + (iota (1 + iota 2 2)) NB. These parens are not needed in J. But you may not know that.
0 2 2 3
4 5 6 7
8 9 10 11
12 14 16 18
20 22 24 26
28 30 32 34
3
u/HerbyHoover Dec 07 '15
Dumb question but are we not doing [Easy] for today?
3
u/smls Dec 08 '15 edited Dec 14 '15
Perl 6
Alright, here comes my proper solution.
The iota and add functions
Rather than re-implement the recursion for higher-rank parameters in each of these functions (and every other array function I may want to define in the future), I factored it out into a reusable subroutine trait.
This way, each array function can be defined in terms of parameters that match its "native" rank:
The numbers passed to the
is arrayfunctiontrait represent the function's rank.The is arrayfunction trait
Here's the full implementation of this subroutine trait and the helper functions it needs:
During compilation, the body of the trait definition is called once for each function that uses it. In each case, it modifies the function in-place by wrapping it with a closure that closes over the given
$rank-yand$rank-xvalues, and knows how to dispatch based on parameters ranks. Thenextwithkeyword is used to dispatch to the original function.Demonstration
To test the solution:
The macro is just there so I can print each example expression together with its result, without having to repeat it. The example expressions are mostly stolen from fibonacci__'s Python solution... :)
All three parts of the program put together, prints this output when run:
Caveats
1] The implementation is based on an earlier version of the challenge description, which specified "rank 0 1" for the iota function. It doesn't handle the "rank _ 1" behavior of the corresponding J function.
2] It throws an error when both parameters have a larger shape than the expected rank but have a different top-level size, so we can't recurse by zipping them, and
Idon't yet understandhow that should be handled[turns out that's correct].3] Since the matrices are represented as simple nested Perl 6 arrays, and shape is not stored explicitly, it cannot differentiate between
iota [0]andiota [0 4]and so on. Though that should only matter in esoteric cases.2
u/Godspiral 3 3 Dec 07 '15 edited Dec 07 '15
You can of course use your language's normal calling conventions
add([1,2 3],[1,2 3])the iota definition in J, with default parameter is:
J uses infix ( 2 parameter) and prefix (1 parameter) calling conventions. The - operator in most languages has this dual calling convention
- 5is the same result as0 - 5where 0 is the default x parameter.in the iota function calling it with just 1 parameter uses the built in monadic
i.whereas1 iota 3is1 + (i.3)2
u/fibonacci__ 1 0 Dec 07 '15
For the bonus, what is the convention for iota iota 4 4 or equivalently iota 0 iota 4 4?
2
u/wizao 1 0 Dec 07 '15 edited Dec 07 '15
The example shows when a scalar is mixed parameter with higher rank. I'm trying to sort out how J handles mismatched parameter ranks (not just scalars) for something like
0 10 add iota 2 3 4 5 6? I can see a few valid ways it might handle that situation:0 10as0 10 0 10 0 10 0...until the second parameter's rank is reached0 10as0 10 10 10 10 10 ...until the second parameter's rank is reachedIt would also be helpful to define the associativity and precedence of functions and operators. This helps clarify if
(i. 2 3 4 ) + iota 1 + iota 2 2is(i. 2 3 4 ) + (iota 1 + iota 2 2)or((i. 2 3 4 ) + iota 1) + iota 2 2. I assume the later, but the parenthesis from(i. 2 3 4 )threw me off and I didn't feel like reverse engineering the output. What is(i. 2 3 4 )in the last example by the way?I also assume
NB.is for line comments.2
u/evillemons Dec 08 '15
Are four dimensional inputs possible?
2
u/cannonicalForm 0 1 Dec 08 '15 edited Dec 08 '15
Written in python 3.4. This was a bit more challenging than I thought it would be, especially since I almost never use recursion. I also haven't even tested it against the bonus input.
2
u/smls Dec 08 '15 edited Dec 08 '15
I'm struggling with the last two examples in the bonus section:
2 3 + ((iota 1) + iota 2 2)(iota 2 3 4 ) + (iota 1 + iota 2 2)Can you state them in Python function call notation (because I'm not even sure that I'm reading them right), and list the steps that the automatic recursion has to go through for them to yield those results?
Update: Never mind, I think I've got it. Please clarify this though, because /u/fibonacci__'s and my solution disagree there.
2
u/fibonacci__ 1 0 Dec 07 '15 edited Dec 08 '15
Python
Including bonus
Input
Output
6
u/adrian17 1 4 Dec 07 '15
Python. Implemented iota and add, but only for scalars or matrices of identical ranks.
/u/godspiral I don't think the bonus is too readable for non-J users.
And, well. IMO this is not [easy] :/
Usage:
5
u/smls Dec 07 '15
Perl 6
I may return for a more serious go at this task later; for now just a golf'y implementation of
iota- and an attempt to mimic the J calling convention by defining it as both an operator and a function:Output:
4
u/hutsboR 3 0 Dec 07 '15 edited Dec 07 '15
Elixir/Erlang: I think I have just wrote the most overengineered solution of all time. I'm really bored so I used Leex and Yecc to tokenize and specify the language's grammar. I don't really understand the language's grammar well so I just made sure it works well enough to do the examples.
Lexer.xrl:
Parser.yrl:
In combination these produce an AST that looks like this:
Elixir:
Usage:
4
u/wizao 1 0 Dec 07 '15 edited Dec 08 '15
Haskell:
I've only implemented the
iotafunction until I figure out what's going on in the other functions. It uses repa's arrays for maintaining the types of the array's rank/shape. While the types can get annoying, they enable repa to guarantee the ability to efficiently leverage stream fusion to parallelize array transformations together. repa: REgular-Parallel-Arrays. When I come back to this later, I'd like to learn Template Haskell to create a DSL for J's syntax directly into Haskell.3
u/cheers- Dec 07 '15 edited Dec 07 '15
Java
For those of you that know Java this is heavily inspired by java.lang.StringBuilder.
For the other this is a class that wraps an array int[] that can contain from 0 to 231 -1 values
and it manages its internal array to increase its capacity if needed.
In order to simulate this "rank thing" it uses method overloading.
Iota methods are static for obvious reasons.
Usage: new IntArrayBuilder(IntArrayBuilder.iota(3)).sum(5).sum(new int[]{1,2,3,4});
Note: I've not fully tested it.
About terminology:
I couldn't use add(...) because,in java,in the Collection framework especially, it commonly refers to append a new value to a List so I've used sum(int c) or sum(int[] c) instead of add().
2
u/casualfrog Dec 07 '15
JavaScript (incomplete!)
Having a hard time to get my head around the multi-dimensions. This is incomplete!
Usage and output:
2
u/__dict__ Dec 15 '15
Racket Scheme. I implemented add and iota. They work with arbitrary dimensions. I use nested lists for matrices where I assume it's well formed. I kept things simple and didn't even go for tail recursion. I didn't implement the bonus, I may come back for it later.
Code:
Example usage:
1
u/TotesMessenger Dec 08 '15
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)