I have an array of boolean values and I want to get the logical and of all elements. What is the most efficient way to do that?
I tried
&([true,false,false]...)
but it throws the error:
syntax: malformed expression
Surprisingly (at least to me) the following expression
|([true,false,false]...)
evaluates to true. So how do I do that? Right now I use a bunch of nots to do that, but this is very unsatisfactory.
Also is this actually better than just looping through all the elements?
Most probably this behavior of & is caused by deprecated ccall functionality where & was used in front of a variable. As explained in the comments above:
you can wrap & in parentheses to make it work as expected(&)([true,false,false]...); however, this is not efficient as you have do splat the passed argument;
if your arguments are all Boll then all function is a recommended way to perform logical and;
if you would need bitwise and then reduce(&, [true,false,false]) is a nice solution as phg indicated.
Related
The docs say that ! is "Boolean not. Implements three-valued logic" and ~ is "Bitwise not."
When should one be used versus the other?
There is a similar question for Python about comparison operators, but I am not sure where the languages may differ.
As you say, ! is boolean not and ~ is bitwise not. This ends up being a bit redundant since bitwise not for booleans is just boolean not so anywhere you can use ! you should also be able to use ~. (This is always true with standard Julia should remain true as long as package don't addg methods that don't conform to the intended meaning of these operators.) So if you're a Matlab programmer, for example, and you're used to using ~ for boolean not, then you can keep doing that. My suggestion, however, would be to be as precise in your meaning as you can be: if you expect the argument to be boolean, use ! so that you get an error if it isn't. Use ~ if you expect the argument to be an integer and want to flip its bits. But frankly it's no big deal to use ~ for booleans. If it really matters that the argument is boolean, like if it's being used in a conditional, then the error will show up soon anyway.
There was a discussion in the lead up to the 1.0 release about removing ! from the language and using ~ for boolean negation instead, but we ended up keeping ! because it's familiar from languages like C and C++ and giving it any other meaning would be actively confusing. But it's telling that removing it was an option in the first place.
I read in several places that pipes in Julia only work with functions that take only one argument. This is not true, since I can do the following:
function power(a, b = 2) a^b end
3 |> power
> 9
and it works fine.
However, I but can't completely get my head around the pipe. E.g. why is this not working?? :
3 |> power()
> MethodError: no method matching power()
What I would actually like to do is using a pipe and define additional arguments, e.g. keyword arguments so that it is actually clear which argument to pass when piping (namely the only positional one):
function power(a; b = 2) a^b end
3 |> power(b = 3)
Is there any way to do something like this?
I know I could do a work-around with the Pipe package, but to honest it feels kind of clunky to write #pipe at the start of half of the lines.
In R the magritrr package has convincing logic (in my opinion): it passes what's left of the pipe by default as the first argument to the function on the right - I'm looking for something similar.
power as defined in the first snippet has two methods. One with one argument, one with two. So the point about |> working only with one-argument methods still holds.
The kind of thing you want to do is called "partial application", and very common in functional languages. You can always write
3 |> (a -> power(a, 3))
but that gets clunky quickly. Other language have syntax like power(%1, 3) to denote that lambda. There's discussion to add something similar to Julia, but it's difficult to get right. Pipe is exactly the macro-based fix for it.
If you have control over the defined method, you can also implement methods with an interface that return partially applied versions as you like -- many predicates in Base do this already, e.g., ==(1). There's also the option of Base.Fix2(power, 3), but that's not really an improvement, if you ask me (apart from maybe being nicer to the compiler).
And note that magrittrs pipes are also "macro"-based. The difference is that argument passing in R is way more complicated, and you can't see from outside whether an argument is used as a value or as an expression (essentially, R passes a thunk containing the expression and a pointer to the parent environment, and automatically evaluates and caches it if you use it as a value; see substitute)
I couldn't find any answers by googling. A coworker mixed up css and xpath predicates and produced the following xpath:
$x("//*[contains(#class, 'btn'[someattr='somevalue'])]")
This xpath returns all elements in the document.
My best understanding is that it is apparently possible to apply predicates to strings ('btn') and that the predicate does not match the string, thus causing the second argument to "contains" to be empty. This would then match all elements because their class attributes contain at least nothing.
But why is this legal?
And is there a way to construct a predicate that would match the string value and thus make the second parameter not empty? I tried a couple things like 'btn'[text()='btn'] but got the same result as the earlier expression.
This is legal in XPath 2.0 but not in 1.0.
In XPath 1.0, the grammar permits a predicate to be applied to any expression, but the type rules say that it's an error if the expression evaluates to anything other than a node-set. (This is a common approach in many languages, to keep the syntax orthogonal but define rules in the type system about which operators can be applied to which values).
In XPath 2.0, all values are sequences, and any sequence can be filtered by a predicate, so it makes perfect sense to filter a sequence of strings, and since a single string is itself a sequence of strings, there is no reason to prohibit that case. In fact it is useful, and I use it frequently: consider:
print("Found " || $n || " error" || "s"[$n gt 1])
Your example would fail even in XPath 2.0, however, because the lhs of the predicate someattr='somevalue' means child::someattr and you can't use an axis expression when the context item is a string.
I have an ifElse Statement which can be of the following two types
a) ifElse(condition, expression_bool_result, expression_bool_result)
whereas expression_bool_result may either be TRUE/FALSE, the result of and(), or(), ==, !=.... or further ifElse
b) ifElse(condition, expression_arith_result, expression_arith_result)
whereas expression_arith_result may either be any number, the result of calculations of further functions returning a number... (or further ifElse)
Since I am new to javacc, I would like to ask you how a production could look like which allows the parser for a clear decision.
Currently I get the warning
Warning: Choice conflict involving two expansions at
line 824, column 5 and line 825, column 5 respectively.
A common prefix is: "ifElse" "("
Consider using a lookahead of 3 or more for earlier expansion.
which - as far as I can tell - implies that my grammer (regarding ifelse) is ambiguous.
If there is no way to write it unambiguously, how could the suggested lookahead look like?
Thanks for your feedback in advance!
No fixed amount of lookahead could possibly resolve this ambiguity in all cases. You could have an arbitrarily long stream of tokens that form a valid expression_arith_result - but is then followed by a comparison operator and another arithmetic value, thus turning it into an expression_bool_result.
The solution would be to have a single ifElse statement, that takes two arbitrary expressions. The required agreement in type between the two expressions would be a matter of semantics, not grammar.
Jason's answer is correct in that you can't resolve the choice with a fixed length of lookahead. However JavaCC does not limit you to fixed length of lookahead. So you can do the following.
void IfExpression() :
{ }
{ LOOKAHEAD( <IFELSE> "(" Condition() "," BooleanExpression() )
BooleanIfExpression()
|
ArithmeticIfExpression()
}
How can i write a substring function in ocaml without using any assignments lists and iterations, only recursions? i can only use string.length.
i tried so far is
let substring s s2 start stop=
if(start < stop) then
substring s s2 (start+1) stop
else s2;;
but obviously it is wrong, problem is that how can i pass the string that is being built gradually with recursive calls?
This feels like a homework problem that is intended to teach you think think about recursion. For me it would be easier to think about the recursion part if you decide on the basic operations you're going to use. You can't use assignments, lists, or iterations, okay. You need to extract parts of your input string somehow, but you obviously can't use the built-in substring function to do this, that would defeat the purpose of the exercise. The only other operation I can think of is the one that extracts a single character from a string:
# "abcd".[2];;
- : char = 'c'
You also need a way to add a character to a string, giving a longer string. But you're not allowed to use assignment to do this. It seems to me you're going to have to use String.make to translate your character to a string:
# String.make 1 'a';;
- : string = "a"
Then you can concatenate two strings using the ^ operator:
# "abc" ^ "def"
- : string = "abcdef"
Are you allowed to use these three operations? If so, you can start thinking about the recursion part of the substring problem. If not, then I probably don't understand the problem well enough yet to give advice. (Or maybe whoever set up the restrictions didn't expect you to have to calculate substrings? Usually the restrictions are also a kind of hint as to how you should proceed.)
Moving on to your specific question. In beginning FP programming, you don't generally want to pass the answer down to recursive calls. You want to pass a smaller problem down to the recursive call, and get the answer back from it. For the substring problem, an example of a smaller problem is to ask for the substring that starts one character further along in the containing string, and that is one character shorter.
(Later on, you might want to pass partial answers down to your recursive calls in order to get tail-recursive behavior. I say don't worry about it for now.)
Now I can't give you the answer to this, Partly because it's your homework, and partly because it's been 3 years since I've touched OCaml syntax, but I could try to help you along.
Now the Basic principle behind recursion is to break a problem down into smaller versions of itself.
You don't pass the string that is slowly being built up, instead use your recursive function to generate a string that is almost built up except for a single character, and then you add that character to the end of the string.