Amend with bond to new data shows unexpected behaviour - j

I have been using J for a couple of weeks now and recently started using it for simple problems rather than just toying with concepts.
This problem needs to replace all x characters in a string into y, which works but using a dyad form of the final verb gives me unexpected output.
Let's use the following example input:
input =. 'abcxdefxghi'
First, I need to find the indexes of x characters in the right argument for amend.
findx =. I.#:([:'x'&= ])
findx input NB. 3 7
0 findx input NB. 3 7
1 findx input NB. 3 7
Then, I amend the results of findx with a bonded y on the left.
trxy =. 'y'&(findx })
trxy input NB. abcydefyghi
_1 trxy input NB. domain error
0 trxy input NB. abcxdefxghi <= this is the really unexpected result
1 trxy input NB. abcydefyghi <= somewhat unexpected, works with strictly positive ints
'a' trxy input NB. domain error
There is two things I don't understand:
why trxy sometimes works as a dyad when I thought I bonded the left side of my amend ?
why a 0 left argument stops trxy from working ?

With 1 trxy input you are executing 1 'y'&(findx }) input – and x u&n y is maybe not what you expect. It is documented (somewhat hidden) on the bottom of this page: https://code.jsoftware.com/wiki/Vocabulary/ampm
It is equivalent to x (m&n # ] ^: [) y, thus applies n on y (with m on the left side) for x times. That's why with 0 trxy y you aren't executing anything, thus y stays the same. With 1 trxy y you are applying trxy once to y. As trxy has no trivial inverse, _1 trxy y results in an error. And because 'a' isn't a number, the last one is just a plain error.
If you – for whatever reason – just want to be able to write trxy as a monad and a dyad that ignores the left-hand side, you could use trxy =. 'y' findx} ]. (As you could also use findx =. I.#:('x' = ]) or just findx =. [:I. 'x'=].)

Related

Create a matrix with random numbers when required shape is derived from other variables

I want to create a matrix with random numbers in J programming language when the required shape is derived from other variables.
I could create such a matrix with ? 3 5 $ 0 if i specify its shape using literal integers. But I am struggling to find a way to create such a matrix when the shape is # y and # x instead of 3 and 5 shown in above example.
I have tried ? 0 $~ # y, # x and it has not worked.
I think I need some way to apply # over a list of variables and return a list of numbers which should be placed after $~, somewhat like map functionality of other languages. Is there a way to do this?
I think that ?#:$ is what you are looking for
3 5 ?#:$ 0
0.031974 0.272734 0.792653 0.439747 0.136448
0.332198 0.00904103 0.7896 0.78304 0.682833
0.27289 0.855249 0.0922516 0.185466 0.257876
The general structure for this is x u#:v y <-> (u (x v y)) where u and v are the verbs and the arguments are x and y.
Hope this helps.
Rereading your question it looks as if you want the shape to be based on the number of items in the arguments. Here I would use # to count the items in each argument, then use , to create the left argument for $&0 and apply ? to the result.
3 4 5 (?#:($&0 #:,))&# 5 3 3 4 5
0.179395 0.456545 0.805514 0.471521 0.0967092
0.942029 0.30713 0.228288 0.693909 0.338689
0.632752 0.618275 0.100224 0.959804 0.517927
Is this closer to what you had in mind?
And as often the case, I thought of another approach overnight
3 4 5 ?#0:"0/ 1 2 3 4 5
0.271366 0.291846 0.0493541 0.72488 0.47988
0.50287 0.980205 0.58541 0.778901 0.0755205
0.0114588 0.523955 0.535905 0.5333 0.984908

Dynamic verb condition in a Do... While (^:)

This question occurred to my while solving this problem.
NB. Find the next number whose prime factorization exponents
NB. match those of the given number.
exps=. /:~#{:#(__&q:)
f=. 3 : 0
target=. exps y
(>:^:(-.#(target-:exps))^:_) y+1
)
f 20 NB. 28
Note that in order to specify the while condition of the Do... While, I first had calculate the prime exponents of the argument y and save that answer to target. I was then able to write -.#(target-:exps) as the While condition.
This of course breaks the tacit style. So I'd like to know if there is a way to achieve the same thing that my verb above achieves, but do so as a single tacit verb?
The way I approached this was to think of f as the centre of a dyadic fork where the left argument is exps y which is the unchanging comparison target and the right argument is >: y which does the initial incrementing. The next step was to use ] at each ^: in f to keep exps monadic. The [ pulls in exps y from the left argument.
Written in tacit
exps=. /:~#{:#(__&q:)
ft=: exps >:#]^:([ -.#-: exps#])^:_ >:
ft 20
28

how dependent bindings in let are evaluated?

Is it safe to use bindings that depend on each other in let? For example:
let x = 1
y = x + 2
in y
Is it possible that they are evaluated in parallel? my ghci shows that it is evaluated correctly, but will this be always the case?
Haskell is lazy evaluated. This means that expressions are only evaluated by necessity. Let's start with your example.
let x = 1
y = x + 2
in y
The system looks at the y part (the expression), and says "Hey. I know what y equals. It equals x + 2" But it can only evaluate x + 2 if it has a definition for x, so it does the same thing and decides that y is 1 + 2 which is of course 3. Now this is only a small portion of the power of lazy evaluation. The next example shows it more fully.
let x = 0 : y
y = 1 : x
in take 50 x
This expression will evaluate correctly, yielding the first fifty elements on the list x, which will be 0 and 1 alternating. Both of the values x and y are infinite lists that depend on each other, and indeed in most languages this would overflow the stack. However, the evaluation rules allow the system to only see the parts it needs, which in that example is the first fifty elements.
So to answer your question about evaluation order, the system evaluates what it sees. If the function is supposed to return y, it evaluates y and then as necessary x. If you had put x in your first example, it would have evaluated x and left y alone. For example, this code will not err.
let x = 1
y = error "I'm an error message!"
in x
This is because the y form is never needed, so the piece of code that would crash the program is never even looked at.
In Haskell (regardless of whether you use a single let, multiple lets, case, where or function parameters) an expression is evaluated when the evaluation of another expression depends on its value.
So in your case, as soon as y's value is required (which of course depends on the surrounding program), y will be evaluated and x will be evaluated as part of y's evaluation.
Another way to think of it is this: whenever you use the value of a variable, it will be evaluated at that point at the latest. That is it might have been evaluated previously (if it was needed previously) or it might be evaluated now, but, as long as you do use the value, it will never not be evaluated. So, except for performance reasons, there's no need to worry about when a variable will be evaluated.

Is it possible to write a J program that uses monadic or dyadic forms of verbs based on execution-time values?

It's cool that 3 * 4 results in 12, and * 4 results in 1, but does using the same primitive for both operations ever provide a benefit? For example, let's say I were to define the following:
SIGNUM =: * : [:
TIMES =: [: : *
If I were to only ever use SIGNUM and TIMES instead of *, would I ever miss out on a clever use of *? That is, x TIMES y seems to be exactly the same as x * y for every x I can imagine (although my imagination is pretty limited in this regard). Is there an x where x * y produces the same result as SIGNUM y?
In case * : [: isn't immediately clear, the following should illustrate:
SIGNUM =: * : [:
TIMES =: [: : *
SIGNUM 4
1
3 TIMES 4
12
* 4
1
3 * 4
12
3 SIGNUM 4
|domain error: SIGNUM
| 3 SIGNUM 4
TIMES 4
|domain error: TIMES
| TIMES 4
Let's write conclusions from the comments down:
There is no direct language-level reason not to use names for primitives
Using names instead of primitives can however harm performance, as special code does not necessarily get triggered. I think this can be remedied by fixing verbs after building them with f..
The reason for having the same name for monadic and dyadic verbs is historical: APL used it before. Most verbs have a related actions in monadic / dyadic versions and inflections (a number of trailing dots and colons).
For instance, ^ can be expressed in traditional notation as pow(x,y) or exp(y) where x and y are left and right arguments, and e is Euler's constant. Here, the monadic version is the same as the dyadic version, with a sensible default left argument. Different inflections of the same root are all power-related verbs:
- ^. does logarithms (base e for the monad)
- ^: does Power conjunction, applying a verb a variable number of times.
Other relations between monadic and dyadic verbs can also exist, for example $ can be said to get or set the Shape of an array, depending on whether it is used as monad or dyad.
That said, I think that once one gets a bit of experience with J, it becomes easier to spot which valence a verb has based on the sentence it is used in. Examples are:
Monad # Ambiv NB. Mv is always used monadically, Av depends on arguments
Ambiv & Monad
(Dyad Monad) NB. A hook, where verb 1 is always dyadic
(Ambiv Dyad Ambiv) NB. A fork, the middle is one always dyadic
It was probably a mistake to use the same symbols for dyadic and monadic built-ins except for those where the monadic case is a default parameter to the dyad.
TIMES =: 1&$: : *
would be a good defnition that doesn't give an error.
As for ambivalent cases,
(3 * TIMES) 4
12
2 (3 * TIMES) 4
24
Another useful ambivalent verb is:
TIMESORSQUARE =: *~
*~ 3
9
2 *~ 3
6

foldList adverb in J

In response to the question of FoldList like primitive in J, I wanted to create an adverb fold so that x u fold y is to fold y with verb u and inital value x:
fold =: 2 : 0
z =.x
for_item. y do. z =. z u item end.
z
)
But I got error when trying it out:
1 (+fold) 1 2 3
|value error: x
| z=. x
what's wrong here? thanks.
Just a couple small things.
First, the numeric code for an adverb is 1. The 2 : 0 you have is defining a conjunction, not an adverb. The way it stands now, J is expecting two direct arguments to fold, and you've only provided one (the +; the two numeric arrays are indirect, not direct, arguments). However, that's not what J is complaining about here, because the other issue is actually tripping it up first. I'll get to that in a second, but nevertheless the first thing you need to do is define fold as an adverb [1].
The more immediate issue that J is complaining about is that it doesn't know what you mean by x. Why? For the same reason that it would if you replaced 2 : 0 (or conjunction define) -- or even, more pertinently, adverb define -- with verb define. Because explicit verbs (direct or derived) are monadic by default and have no x argument (hence mentioning x is a value error). If you want to define a dyadic verb, you must ask for it explicitly.
Now, defining a dyadic verb directly is straightforward: instead of saying verb define, you simply say dyad define. But deriving a dyadic verb from a modifier (adverb or conjunction) is a little less obvious. You must use the special colon syntax which allows you to separate the monadic and dyadic valences of explicit definitions. This syntax applies to all explicit definitions, including verbs, adverbs, and conjunctions, but for adverbs and conjunctions it is the only way to derive an explicit verb.
Bottom line:
fold =: adverb define
NB. Note solitary colon on next line. Everything after that is dyadic.
:
z =.x
for_item. y do. z =. z u item end.
z
)
[1]: You may find using the standard covers for nameclasses easier to remember (and read later), as in adverb define and conjunction define (for one-liners, you can use def in place of define).

Resources