This question already has answers here:
Is there a built-in way to compare two iterators?
(2 answers)
Closed 3 years ago.
I want to compare to iterators in a test case. Unfortunately, assert_eq! does not like to be passed iterators.
One workaround looks like this:
let mut a = 0..5;
let mut b = 0..6;
assert!(a.by_ref().zip(b.by_ref()).all(|(a, b)| a == b));
assert_eq!(a.next(), None);
assert_eq!(b.next(), None);
But it requires 3 (or at least) 2 lines for the test and the iterator needs to be made mutable. Is there anything better?
There is Iterator::eq. I think this should be the winner:
assert!(a.eq(b));
And it turns out there is itertools::assert_equal:
let a = 0..6;
let b = 0..6;
itertools::assert_equal(a, b);
And it's not exactly pretty but here is a solution using zip_longest:
assert!(a.zip_longest(b).all(|thingy| thingy.as_ref().left() == thingy.as_ref().right()));
Related
I have a sum type representing arithmetic operators:
data Operator = Add | Substract | Multiply | Divide
and I'm trying to write a parser for it. For that, I would need an exhaustive list of all the operators.
In Haskell I would use deriving (Enum, Bounded) like suggested in the following StackOverflow question: Getting a list of all possible data type values in Haskell
Unfortunately, there doesn't seem to be such a mechanism in Idris as suggested by Issue #19. There is some ongoing work by David Christiansen on the question so hopefully the situation will improve in the future : david-christiansen/derive-all-the-instances
Coming from Scala, I am used to listing the elements manually, so I pretty naturally came up with the following:
Operators : Vect 4 Operator
Operators = [Add, Substract, Multiply, Divide]
To make sure that Operators contains all the elements, I added the following proof:
total
opInOps : Elem op Operators
opInOps {op = Add} = Here
opInOps {op = Substract} = There Here
opInOps {op = Multiply} = There (There Here)
opInOps {op = Divide} = There (There (There Here))
so that if I add an element to Operator without adding it to Operators, the totality checker complains:
Parsers.opInOps is not total as there are missing cases
It does the job but it is a lot of boilerplate.
Did I miss something? Is there a better way of doing it?
There is an option of using such feature of the language as elaborator reflection to get the list of all constructors.
Here is a pretty dumb approach to solving this particular problem (I'm posting this because the documentation at the moment is very scarce):
%language ElabReflection
data Operator = Add | Subtract | Multiply | Divide
constrsOfOperator : Elab ()
constrsOfOperator =
do (MkDatatype _ _ _ constrs) <- lookupDatatypeExact `{Operator}
loop $ map fst constrs
where loop : List TTName -> Elab ()
loop [] =
do fill `([] : List Operator); solve
loop (c :: cs) =
do [x, xs] <- apply `(List.(::) : Operator -> List Operator -> List Operator) [False, False]
solve
focus x; fill (Var c); solve
focus xs
loop cs
allOperators : List Operator
allOperators = %runElab constrsOfOperator
A couple comments:
It seems that to solve this problem for any inductive datatype of a similar structure one would need to work through the Elaborator Reflection: Extending Idris in Idris paper.
Maybe the pruviloj library has something that might make solving this problem for a more general case easier.
This question already has answers here:
Does Objective-C use short-circuit evaluation?
(4 answers)
Closed 6 years ago.
I can't test this well but I was wondering if someone might know this. Having this simple check
if ([dict objectForKey:#"key"] != nil || [a isEqualToString:b] || someIntValue> 12) { ... }
Obviously (no matter the small margin) the first check will probably be heavier than the second, and the third even lighter.
So my question is; will the binary in my app still check the other 2 statements if the first was already true? Because if so I was thinking of doing a small round checks in my code-base to tweak checks like those above to move the simple int comparison earlier in that if-statement.
p.s.
I know you can't check unexisting objects in Objective-C like you can in PHP and I also only mean existing objects in this example, not to do something hacky that object(s) in the second statement won't exist:
$a = 0; $b = '';
if ($a == 0 || $i_dont_exist > 0) {
...
}
This is called short-circuit evaluation. Objective-C is a strict superset of C, since C supports short-circuit evaluation so does Objective-C.
So if the first condition in an "or" statement is true the rest of the conditions should not be evaluated.
This question already has answers here:
Inheritance for metamethods in Lua
(3 answers)
Closed 6 years ago.
I'm trying to implement simple inheritance in Lua as it is presented in PIL 16.2. However, I've come across a surprising behavior: metamethods don't seem to be inherited. In the following example, I create a Point class with x and y members, and give it an __add metamethod. When adding instances of Point, everything works fine, but if I create a subclass and add instances of that, I get an error.
Point = {}
function Point:new(x, y)
local point = {}
setmetatable(point, self)
self.__index = self
point.x = x or 0
point.y = y or 0
return point
end
Point.__add = function(a, b)
return Point:new(a.x + b.x, a.y + b.y)
end
p = Point:new(2,2)
r1 = p + p
print(p.x, p.y) -- prints "4 4" as expected
ChildPoint = Point:new()
c = ChildPoint:new()
r2 = c + c -- Error: attempt to perform arithmetic on a table value (local 't1')
print(r.x, r.y)
I was expecting that Lua would look for __add in ChildPoint, and that would trigger ChildPoint's __index, finding __add in Point. But that does not seem to happen.
Why does this not work, what actually happens, and (if this is correct behavior and not just a mistake of mine) how do I implement inheritable metamethods in Lua?
As Egor explained, the metamethods need to be copied explicitly in this case; see this earlier SO question for the discussion of the same problem and possible solutions (the selected one copies the metamethods).
This question already has answers here:
Why is NaN not equal to NaN? [duplicate]
(6 answers)
Closed 8 years ago.
isNan is defined like this in iOS SDK, math.h as below,
#define isnan(x) \
( sizeof(x) == sizeof(float) ? __inline_isnanf((float)(x)) \
: sizeof(x) == sizeof(double) ? __inline_isnand((double)(x)) \
: __inline_isnanl((long double)(x)))
And the inline function goes like this,
__header_always_inline int __inline_isnanf(float __x) {
return __x != __x;
}
__header_always_inline is just to force the compiler to make the function surely inline.
What actually has been done in the inline function is pretty evasive to my eyes.
return __x != __x;
What does this line do? How does it verify if the argument is a NaN or not?
Edit:
The question here is NOT why NaN is not equal to NaN; but how its implemented. So please guide your answers towards the actual low level implementation.
Any help is greatly appreciated. Thanks.
CF http://en.wikipedia.org/wiki/NaN
A comparison with a NaN always returns an unordered result even when comparing with itself.
Mean a NaN is ALWAYS different from what you compare it too :)
I suppose the compiler/CPU has their own way to check for this special value, maybe someone can give a better answer than me about the implementation...
This question already has answers here:
Why are variables "i" and "j" used for counters?
(23 answers)
Closed 9 years ago.
I assume there is some historical/mathematical reason that whenever I write I for loop, I use i:
for (var i=0; i<10; i++) {
// do something 10 times
}
I know i is used in mathematics for summations (Σ) and products (∏). Does it just mean "index", or is there some more significant meaning?
I believe it does just mean "index" in the example mentioned.
I know it's not answering your question and probably stating the obvious but I personally would always try to give the variable name some meaning for readability and avoid this confusion when reading others code e.g.
for (int productCounter = 0; productCounter<10; productCounter++){
// do something 10 times
}
In Fortran, variables starting with letters I through M were automatically of type INTEGER, so people could write:
DO 10 J = 1, 10
...do something 10 times...
10 CONTINUE
Labels were numeric in columns 1-5; column 6 was for the continuation character (if needed), and the code started in column 7 (originally up to column 72; column 73-80 on the punched card were for the card's sequence number in the deck).
Single letter names are convenient. In Fortran, you didn't have to declare the variables before you used them.