J function is not working - math

I am a complete beginner to J. My first attempt at writing a function is something like the totient function. It takes an array, assumed to be i.num for some number, num. And then computes the number of elements coprime to the tally of the array.
If I do it manually like this:
numbers =: i.7
#(1=( #numbers)+./numbers)#numbers
it works. The result is 6.
So I want to turn this into a general function.
Tot =: monad :'(1=( #x)+./x)#x'
Tot i.11
This fails and I get a value error for x. I don't know why.

The monad's variable should be y, not x:
Tot =: monad :'(1=( #y)+./y)#y'
x is the left argument of a dyad.

Related

Trouble understanding OCAML power function

I'm trying to make sense of this Caml function to calculate the n-th power of a number.
let rec iterate n f d =
if n = 0 then d
else iterate (n-1) f (f d)
let power i n =
let i_times a = a * i in
iterate n i_times 1
I understand what it does conceptually, but I am having trouble understanding the i_times bit.
Per my understanding, i_times takes a value a and returns a*i, whre i is passed onto power upon calling it. In the expression where i_times is defined, it's followed by 1, so wouldn't this mean that i_times 1, all together, is evaluated to 1*i?
In this case, I fail to see how 3 parameters are being passed to iterate. Why doesn't it just end up being 2, that is n and i_times 1?
I know this is a pretty basic function, but I'm just getting started with functional programming and I want to make sense of it.
Basically you're asking how OCaml parses a series of juxtaposed values.
This expression:
f a b c
is iterpreted as a call to a function f that passes 3 separate parameters. It is not parsed like this:
f a (b c)
which would be passing 2 parameters to f.
So indeed, three parameters are being passed to iterate. There are no subexpressions in the list of parameters, just three separate parameters.
Why didn't you figure that the subexpression n i_times would be evaluated before calling iterate? The reason (I suspect) is that you know that n isn't a function. But the parsing of the language doesn't depend on the types of things. If you wrote (n i_times) (with parentheses) it would be parsed as a call to n as a function. (This would, of course, be an error.)

What are the rules for threading a function over a vector in R?

I have some code which I call with two vectors of different length, lets call them A and B. However, I wrote the function having in mind a single element of A with the expectation that it will be automatically threaded over A. To be concrete,
A <- rnorm(5)
B <- rnorm(30)
foo <- function(x,B){
sum( cos(x*B) ) # calculate sum_i cos(x*B[i])
}
sum( exp(foo(A,B)) ) # expecting this to calculate the exponent for each A[j] and add over j
I need to get
Σ_j exp( Σ_i cos(A[j]*B[i])
and not
Σ_ij exp(cos(A[j]*B[i])) OR exp(cos(Σ_ij A[j]*B[i]))
I suspect that the last R expression is ambiguous, since the declaration of foo does not know B is always a vector. What are the formal rules and am I right to worry about the ambiguity?
If we want to loop over the 'A', then use sapply , and apply the foo on each of the elements of 'A' with anonymous function call and get the sum of the output vector
sum(exp(sapply(A, function(x) foo(x, B))))
In the OP's example with the expression foo(A, B), the product A*B is computed first, and since the lengths of A and B are unequal, the recycling rule takes priority. There is no error message coming out, just because by pure luck the vector length of one is a multiple of the other.
You can also Vectorize the x input. I think this is what you were expecting. At the end of the day, this will work it's way down to an mappy() implementation which is a multivariate sapply, so probably best to just do it yourself as with the solution from akrun.
foo2 <- Vectorize(foo, "x")
sum(exp(foo2(A, B)))
The "formal rules" as you put them is quite simply how R does help("Arithmetic").
The binary operators return vectors containing the result of the element by element operations. If involving a zero-length vector the result has length zero. Otherwise, the elements of shorter vectors are recycled as necessary (with a warning when they are recycled only fractionally). The operators are + for addition, - for subtraction, * for multiplication, / for division and ^ for exponentiation.
So when you use x*B, it is doing element-wise multiplication. Nothing changes when you pass A into the function instead of x.
Simply go through your lines one at a time.
x*B will be a vector of length max(length(x, B)). When they are not of the same length, R will recycle elements of the shorter vector (i.e., repeat them).
cos(x*B) will be a vector of the same length as step (1), but now the cosine of that value.
sum( cos(x*B) ) will sum that vector, returning a single number.
foo(A,B) does steps (1) through (3), but with your defined A and B. Note that in your example A is recycled 6 times to get to the length of B. In other words, what you entered as A is being used as rep(A, 6) in the multiplication step. Nothing about a function definition in R says that foo(A,B) should be repeated for each element of vector A. So it behaves literally as you wrote it, basically swapping in A for x in the function code.
exp(foo(A,B)) will take the result from foo from step 3 (which is a scalar) and raise it to an exponent.
sum( exp(foo(A,B)) ) does nothing, since step (5) is a scalar, there is nothing to sum.

How to properly iterate through two-dimensions array and sum all the lengths of elements?

I've encountered a problem when trying to iterate through two dimension array and summing up the lengths of all elements inside in prolog.
I've tried iterating through a simple 1D array and result was just as expected. However, difficulties appeared when I started writing the code for 2D array. Here's my code :
findsum(L):-
atom_row(L, Sum),
write(Sum).
atom_row([Head|Tail], Sum) :-
atom_lengths(Head, Sum),
atom_row(Tail, Sum).
atom_row([], 0).
atom_lengths([Head|Tail], Sum):-
atom_chars(Head, CharList),
length(CharList, ThisLenght),
atom_lengths(Tail, Temp),
Sum is Temp + ThisLenght,
write(ThisLenght).
atom_lengths([], 0).
For example, sum of the elements in array [[aaa, bbbb], [ccccc, dddddd]] should be equal to 18. And this is what I get:
?- findsum([[aaa, bbbb], [ccccc, dddddd]]).
436
false.
The output comes from write(ThisLength) line after each iteration.
Typically it helps (a lot) by splitting the problem into simpeler sub-problems. We can solve the problem, for example, with the following three steps:
first we concatenate the list of lists into a single one-dimension list, for example with append/2;
next we map each atom in that list to the length of that atom, with the atom_length/2 predicate; and
finally we sum up these values, for example with sum_list/2.
So the main predicate looks like:
findsum(LL, S) :-
append(LL, L),
maplist(atom_length, L, NL),
sumlist(NL, S).
Since maplist/3 is a predicate defined in the library(apply), we thus don't need to implement any other predicates.
Note: You can see the implementions of the linked predicates by clicking on the :- icon.
For example:
?- findsum([[aaa, bbbb], [ccccc, dddddd]], N).
N = 18.

prolog factorial recursion giving expression as output

I've written a prlog recursive factorial clause which is:
factorial(X,Y):-
(X>1)
-> factorial(X-1,X*Y)
; write(Y).
The problem is, for any valid call[for example, factorial(5,1). ], it is giving an expression rather than a value[(5-1-1-1)* ((5-1-1)* ((5-1)* (5*1)))]. How can I get a value rather than an expression.
The comment by #lurker is a bit simplistic. Comparison operators do evaluate expressions. So, your code could be made to work:
factorial(X,Y):- X>1 -> factorial(X-1,F), Y=X*F ; Y=1.
?- factorial(5,X),F is X.
X = 5*((5-1)*((5-1-1)*((5-1-1-1)*1))),
F = 120.

How to know the index of the iterator when using map in Julia

I have an Array of arrays, called y:
y=Array(Vector{Int64}, 10)
which is basically a list of 1-dimensional arrays(10 of them), and each 1-dimensional array has length 5. Below is an example of how they are initialized:
for i in 1:10
y[i]=sample(1:20, 5)
end
Each 1-dimensional array includes 5 randomly sampled integers between 1 to 20.
Right now I am applying a map function where for each of those 1-dimensional arrays in y , excludes which numbers from 1 to 20:
map(x->setdiff(1:20, x), y)
However, I want to make sure when the function applied to y[i], if the output of setdiff(1:20, y[i]) includes i, i is excluded from the results. in other words I want a function that works like
setdiff(deleteat!(Vector(1:20),i) ,y[i])
but with map.
Mainly my question is that whether you can access the index in the map function.
P.S, I know how to do it with comprehensions, I wanted to know if it is possible to do it with map.
comprehension way:
[setdiff(deleteat!(Vector(1:20), index), value) for (index,value) in enumerate(y)]
Like this?
map(x -> setdiff(deleteat!(Vector(1:20), x[1]),x[2]), enumerate(y))
For your example gives this:
[2,3,4,5,7,8,9,10,11,12,13,15,17,19,20]
[1,3,5,6,7,8,9,10,11,13,16,17,18,20]
....
[1,2,4,7,8,10,11,12,13,14,15,16,17,18]
[1,2,3,5,6,8,11,12,13,14,15,16,17,19,20]

Resources