list comprehension without parentheses in a function - coffeescript

I have a function that needs to return the last property of an object that satisfies the condition:
types = {
a: 1,
b: 2,
c: 3
}
g = (s) -> v for k, v of types when k is s
console.log g 'b'
this code prints [ 2 ]
I expected just 2, and not an array. And indeed, this code does print what I expect:
console.log v for k, v of types when k is 'b'
What is wrong?
P.S. I know that instead of this function I can just access the object's property using [], but this is a contrived example.

If we rearrange the code then things should be clearer.
Your second piece of code:
console.log v for k, v of types when k is 'b'
is just another way of writing this:
for k, v of types when k is 'b'
console.log(v)
or even:
for k, v of types
if k is 'b'
console.log(v)
Since there is only one 'b' key, only one console.log call is made.
Your first piece of code:
g = (s) -> v for k, v of types when k is s
is the same as this:
g = (s) ->
a = (v for k, v of types when k is s)
a
The loop, v for k, v of types when k is s yields an array by definition so a will be an array (with only one element) and g will return an array.

console.log v for k, v of types when k is 'b' will call console.log(v) for every v when k satisfies the condition whereas your first code snipped will call console.log(g(b)). If there were two elements in types that satisfied the condition, the outputs would be:
[1, 2]
and
1
2
To make g output the first element that satisfies the condition, you could use return with early out or just take the first element of the results array.
g = (s) -> return v for k, v of types when k is s

Related

Explanation of class instance declarations

I am following a tutorial and found this code:
data A = B | C deriving(Eq)
class K a where
f :: a -> Bool
instance K A where
f x = x == C
f _ = False
call = f B
Why do I need f _ = False? I get the same result without it.
The answer is simply: you don't need f _ = False here. In fact, if you compile with -Wall then the compiler will warn you that this clause is redundant, because the f x = ... clause already catches everything.
If the tutorial told you to have that extra clause, well, it's wrong.
As pointed out, it's not necessary.
You might need (or want) that line, though, if you had a slightly different definition, one that does not require an Eq instance:
data A = B | C
class K a where
f :: a -> Bool
instance K A where
f C = True
f _ = False
Instead of comparing x to C, you can match the argument directly against C, then define f to return False for all other values. This makes more sense if there were more constructors that could produce False.
data A' = B | C | D
instance K A' where
f C = True
f _ = False -- in place of f B = False and f D = False

How to know which Maple command automatically maps on list entries or not?

In Mathematica, almost all commands automatically thread (or map) over a list.
In Maple, how does one determine which command automatically acts over entries of a list or a set?
For example:
y+p*x=2*sqrt(x*y);
r:=[solve(%,y)];
This gives list of two entries (the solutions)
#r := [-p*x+(2*(1+sqrt(1-p)))*x, -p*x+(2*(1-sqrt(1-p)))*x]
Now I found that collect automatically maps on each list entry
collect(r,x);
# [(-p+2+2*sqrt(1-p))*x, (-p+2-2*sqrt(1-p))*x]
But another command does not (I just picked this one)
MmaTranslator[Mma][LeafCount](r);
#37
For the above one needs to explicitly iterate over the entries of a list or a set.
map(MmaTranslator[Mma][LeafCount],r)
#[17, 19]
Is there a way in Maple to find which command automatically threads over entries of a list or a set other than trial and error?
Maple 2018.1
I don't know of any place in the documentation that says exactly which commands will automatically map over a list.
But the collection of such commands is not large. The vast majority of commands will not automatically map over a list. Most of the ones which auto-map over a list relate to simplication or related manipulation of expressions. The collection of commands which auto-map over a list contains at least these:
collect, combine, expand,
evala, evalc, evalf,
factor, normal, radnormal, rationalize, simplify
The auto-mapping over lists for those commands is mostly a convenience to provide a shorter syntax than wrapping explicitly with the map command.
There are also commands which preserve structure (unless explicitly
told, via options, that the outer list structure is the thing to alter) and thus usually accomplish the same thing for a list as mapping over the list:
convert, eval, evalindets, subs, subsindets
Modern Maple has another shorter syntax which can map a command over a list (or a set, or a Vector, etc). It is called the "elementwise" operation, and its syntax consists of appending ~ (tilde) to the command.
Eg,
discont~( [ csc(x), sec(x) ], x );
[{Pi _Z1~}, {Pi _Z2~ + 1/2 Pi}]
As far as your other example goes, note that LeafCount computes a value (metric) for the first argument considered as a single expression. But a list of items is still a single expression. So it certainly should not be surprising that (without the ~) it acts on the list as a whole, rather than automatically mapping over it. It counts the enclosing list as an additional "leaf".
MmaTranslator:-Mma:-LeafCount( L0 );
8
L0 := [ sin(x), 1/2*x*cos(x) ]:
MmaTranslator:-Mma:-LeafCount~( L0 );
[2, 5]
map( MmaTranslator:-Mma:-LeafCount, L0 );
[2, 5]
For an example similar to your original there is no difference in applying collect (which auto-maps) and applying it elementwise with collect~. Here, the first two results are the same because the addtional argument, x, happens to be a scalar. Eg,
r := [p*x+(2*(x^2+p^2))*x, p*x+(2*(x^2-p^2))*x]:
collect(r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
collect~(r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
map(collect, r, x);
3 2 3 2
[2 x + (2 p + p) x, 2 x + (-2 p + p) x]
I should mention that the above examples will behave differently if the second argument is a list such as [x,p] rather than a scalar such as x.
s := [a*b+(2*(a^2*b+b^2))*a, a*b+(2*(a^2*b-b^2))*a]:
collect(s, [a,b]);
3 2 3 2
[2 b a + (2 b + b) a, 2 b a + (-2 b + b) a]
map(collect, s, [a,b]);
3 2 3 2
[2 b a + (2 b + b) a, 2 b a + (-2 b + b) a]
collect~(s, [a,b]);
3 2 2 3
[2 b a + (2 b + b) a, -2 a b + (2 a + a) b]
zip(collect, s, [a,b]);
3 2 2 3
[2 b a + (2 b + b) a, -2 a b + (2 a + a) b]
In the above, the elementiwise collect~ example acts like zip when the second argument is also a list. That is, the first item in the first argument is collected wrt the first item in the second argument, and the second item in the first argument is collected wrt to the second item in the second argument.
Another feature of the elementwise operator syntax is that it will not map the command over the operands of a scalar expression (ie. not a list, set, Vector, etc). This is in stark contrast to map, which can be used to map an operation over the operands of an expression.
Here are two examples where map applies the command to the operands of a scalar expression, while using elementwise ~ gets the command applied only to the scalar expression itself. In the first example the operands are the summands of a sum of terms. In the second example the operands are the arguments of an unevaluated function call.
T := x^2 * sin(x) + y^2 * cos(x):
F( T );
2 2
F(x sin(x) + y cos(x))
F~( T );
2 2
F(x sin(x) + y cos(x))
map( F, T );
2 2
F(x sin(x)) + F(y cos(x))
G( arctan(a, b) );
G(arctan(a, b))
G~( arctan(a, b) );
G(arctan(a, b))
map( G, arctan(a, b) );
arctan(G(a), G(b))
So, if you don't want to map a command inadvertantly over the operands of a scalar expression (addend, multiplicands, etc) then you can use the elementwise ~ syntax without having to first test whether the first expression is a scalar or a list (etc).
Again, if there is an additional argument then it makes a difference whether it is a scalar to a list.
F( T, a );
F(sin(x) + cos(x), a)
F~( T, a );
F(sin(x) + cos(x), a)
map( F, T, a );
F(sin(x), a) + F(cos(x), a)
F( T, [a,b] );
F(sin(x) + cos(x), [a, b])
map( F, T, [a,b] );
F(sin(x), [a, b]) + F(cos(x), [a, b])
F~( T, [a,b] );
[F(sin(x) + cos(x), a), F(sin(x) + cos(x), b)]
zip( F, T, [a,b] );
[F(sin(x) + cos(x), a), F(sin(x) + cos(x), b)]

Supplying section arguments for examples

Consider this section:
Section MyMap.
Variables D R : Type.
Fixpoint mymap (f : D -> R) (l : list D) : list R :=
match l with
| nil => nil
| d :: t => f d :: mymap f t
end.
End MyMap.
Here I've used Variables to declare my domain and range types. As a sanity check on the definition of my function, I would like to include an Example:
Example example_map_S : mymap S [0; 1; 2] = [1; 2; 3].
Proof.
simpl; trivial.
Qed.
However it seems I can't do so within my section. Instead I get:
Error: The term "S" has type "nat -> nat" while it is expected to have type "D -> R".
That's not too surprising, so let's try it another way:
Example example_map_S : #mymap nat nat S [0; 1; 2] = [1; 2; 3].
Proof.
simpl; trivial.
Qed.
Which produces:
Error: The term "nat" has type "Set" while it is expected to have type "D -> R".
I suppose that's fair, section-ized Variables aren't the same thing as implicit arguments. But it still leaves the question!
How can I supply concrete Variables to a term before closing the section, in order to create useful Examples?
Section MyMap.
...
If we check the type of mymap inside the section, we get
Check mymap.
(* mymap : (D -> R) -> list D -> list R *)
Of course, we can't unify D and R with nat, since D and R are some locally postulated types.
However, we can sort of simulate your example in this generalized setting, showing the expected property of the mymap function:
Example example_nil (f : D -> R) :
mymap f [] = [] := eq_refl.
Example example_3elems (f : D -> R) (d0 d1 d2 : D) :
mymap f [d0; d1; d2] = [f d0; f d1; f d2] := eq_refl.
End MyMap.

Building a recursive string function

I am trying to build a function whose output is a list of all possible boolean expressions with an upper bound. For three variables p,q and r my function would be, theoretically:
f(0) = {p,q,r} // this notation refer to the mathematical set such that p,q and r belong to f(0).
f(n+1) = { (A & B) such that A and B belongs to f(n) } Union { (A or B) such that A and B belongs to f(n) } Union { (not A) such that A belongs to f(n) }
I want to receive a matrix whose rows are the strings of all the possible strings corresponding to boolean formulas build by n iterations of the function. For example:
f(2)=['p' ; 'q' ; 'r' ; '(p&q)' ; 'p&(p or q)' ; 'r or (p & r)' ; ... ]

Using each right to pass parameters to a kdb function

I have the following code that does not work:
fun { [h; d]
h(anotherFun; d)
}
h: hopen(`hparam)
d: (2013.06.01, 2013.06.02)
h,/:fun d
What do I need to do to call fun with h and each element of d? The diagnostic from q is cryptic to say the least.
it seems like h and elements of d are your two arguments so you can try
h fun/: d
Easiest would be create projection with constant argument and just call it for each argument from the list
fun[h;] each d