What does (x & (x >> 1) == 0) check for? - language-agnostic

I saw this statement in a large code base, and I don't know what this check using bit manipulation is for. Is this some standard trick in bit manipulation? If so, what is it looking for?
I know that in binary, x >> 1 shifts all the bits of x to the right 1 place, so anding that with x will guarantee the largest set bit of x becomes zero. But I just don't understand the purpose of this check.

(x & (x >> 1)) == 0 (extra parentheses added for safety) checks if there are adjacent set bits in x, and evaluates to true if there aren't.
For example:
10101010 -> true
00010000 -> true
00000011 -> false
10100110 -> false

Related

Is it possible find the values โ€‹of the two variables a and x in the function y = (a ^ k) ^ (x ^ k), i know only the y and the k

I would like to know if it is possible to create a function, using logic gates for binary numbers, such that i can go back to the two variables a and x, knowing only y and k.
I used the XOR logic gate but, if this is indeed possible, you can also change it to any other gate, I accept any kind of advice!
y = (a ^ k) ^ (x ^ k)
That's a SAMPLE of the function that i must find, if it can be solved in other simpler ways let me know! Thank you
i'm assuming that ^ here means xor and not exponentiation.
Remember that ^ is both associative and commutative, so
y = (a ^ k) ^ (x ^ k) == a ^ x ^ k ^ k = a ^ x ^ (k ^ k) = a ^ x ^ 0 = a ^ x
The value of k is completely irrelevant in this expression, so knowing the value of k tells you absolutely nothing.
Knowing the values of two of a, x, or y, you find find the third by xor-ing the other two. You cannot find the value of k if you don't know it.
You can, in a sense. What we know about the normal math we have encountered our whole lives is not the same here, so solving for a and x will not be so explicit. Firstly, there is not a nice concept of moving variables from one side of the equation to the other in boolean algebra. Second, the XOR function is not a continuous function, therefore it can only be expressed as a piecewise function. What that all means is solving for a and x is not going to happen like we're used to.
Let's break it apart to make it more clear.
y = f1 ^ f2
where f1 = (a^k)
where f2 = (x^k)
All we did here was to make a smaller function for each parenthesis.
Let's define f1 (XOR).
f1 = 0, a=k
f1 = 1, a!=k
Let's define f2 (XOR).
f2 = 0, x=k
f2 = 1, x!=k
Now, let's define y (XOR)
y = 0, f1=f2
y = 1, f1!=f2
If you know y, then you can determine whether f1 and f2 are equal or not. Since f1 and f2 are constructed the same way, they are identical except for their input arguments a and x. From this point, if you know k, you can show that if f1=f2, then a=x. You can also show that if f1!=f2, then a!=x. You can say how a and x are related, but unfortunately, you cannot determine their values. I urge you to try plugging it in yourself, you will find a and x can have two different values for each value of y.

Operator overloading in Isabelle

I want to use the nat type in Isabelle but I want to overload some existing definitions like for example addition. I wrote the following code:
theory Prueba
imports Main HOL
begin
primrec suma::"nat โ‡’ nat โ‡’ nat" where
"suma 0 n = 0" |
"suma (Suc x) n = 0"
no_notation suma (infix "+" 65)
value "2 + (1 :: nat)"
I tried to overload addition with a new definition that always outputs 0. However when I evaluate 2 + (1 :: nat) I get "Suc (Suc (Suc 0))" :: "nat", which means Isabelle is still using the plus definition from Nat. How can I get it to use my new definition of +?
Thank you
Your must use no_notation to remove the default plus-syntax which comes from the plus type class of the Groups theory.
no_notation Groups.plus_class.plus (infixl "+" 65)
Then you can use
notation suma (infixl "+" 65)
to add your own syntax.
(I have never tried to override such basic parts of the definitions. I guess it might lead to strange situations โ€“ especially for other people trying to work with your theory afterwards.)

Binary to decimal - prolog

I found this on stack: reversible "binary to number" predicate
But I don't understand
:- use_module(library(clpfd)).
binary_number(Bs0, N) :-
reverse(Bs0, Bs),
binary_number(Bs, 0, 0, N).
binary_number([], _, N, N).
binary_number([B|Bs], I0, N0, N) :-
B in 0..1,
N1 #= N0 + (2^I0)*B,
I1 #= I0 + 1,
binary_number(Bs, I1, N1, N).
Example queries:
?- binary_number([1,0,1], N).
N = 5.
?- binary_number(Bs, 5).
Bs = [1, 0, 1] .
Could somebody explain me the code
Especialy this : binary_number([], _, N, N). (The _ )
Also what does library(clpfd) do ?
And why reverse(Bs0, Bs) ? I took it away it still works fine...
thx in advance
In the original, binary_number([], _, N, N)., the _ means you don't care what the value of the variable is. If you used, binary_number([], X, N, N). (not caring what X is), Prolog would issue a singleton variable warning. Also, what this predicate clause says is that when the first argument is [] (the empty list), then the 3rd and 4th arguments are unified.
As explained in the comments, use_module(library(clpfd)) causes Prolog to use the library for Constraint Logic Programming over Finite Domains. You can also find lots of good info on it via Google search of "prolog clpfd".
Normally, in Prolog, arithmetic expressions of comparison require that the expressions be fully instantiated:
X + Y =:= Z + 2. % Requires X, Y, and Z to be instantiated
Prolog would evaluate and do the comparison and yield true or false. It would throw an error if any of these variables were not instantiated. Likewise, for assignment, the is/2 predicate requires that the right hand side expression be fully evaluable with specific variables all instantiated:
Z is X + Y. % Requires X and Y to be instantiated
Using CLPFD you can have Prolog "explore" solutions for you. And you can further specify what domain you'd like to restrict the variables to. So, you can say X + Y #= Z + 2 and Prolog can enumerate possible solutions in X, Y, and Z.
As an aside, the original implementation could be refactored a little to avoid the exponentiation each time and to eliminate the reverse:
:- use_module(library(clpfd)).
binary_number(Bin, N) :-
binary_number(Bin, 0, N).
binary_number([], N, N).
binary_number([Bit|Bits], Acc, N) :-
Bit in 0..1,
Acc1 #= Acc*2 + Bit,
binary_number(Bits, Acc1, N).
This works well for queries such as:
| ?- binary_number([1,0,1,0], N).
N = 10 ? ;
no
| ?- binary_number(B, 10).
B = [1,0,1,0] ? ;
B = [0,1,0,1,0] ? ;
B = [0,0,1,0,1,0] ? ;
...
But it has termination issues, as pointed out in the comments, for cases such as, Bs = [1|_], N #=< 5, binary_number(Bs, N). A solution was presented by #false which simply modifies the above helps solve those termination issues. I'll reiterate that solution here for convenience:
:- use_module(library(clpfd)).
binary_number(Bits, N) :-
binary_number_min(Bits, 0,N, N).
binary_number_min([], N,N, _M).
binary_number_min([Bit|Bits], N0,N, M) :-
Bit in 0..1,
N1 #= N0*2 + Bit,
M #>= N1,
binary_number_min(Bits, N1,N, M).

Defining a Racket Function?

I'm supposed to define the function n! (N-Factorial). The thing is I don't know how to.
Here is what I have so far, can someone please help with this? I don't understand the conditionals in Racket, so an explanation would be great!
(define fact (lambda (n) (if (> n 0)) (* n < n)))
You'll have to take a good look at the documentation first, this is a very simple example but you have to understand the basics before attempting a solution, and make sure you know how to write a recursive procedure. Some comments:
(define fact
(lambda (n)
(if (> n 0)
; a conditional must have two parts:
; where is the consequent? here goes the advance of the recursion
; where is the alternative? here goes the base case of the recursion
)
(* n < n))) ; this line is outside the conditional, and it's just wrong
Notice that the last expression is incorrect, I don't know what it's supposed to do, but as it is it'll raise an error. Delete it, and concentrate on writing the body of the conditional.
The trick with scheme (or lisp) is to understand each little bit between each set of brackets as you build them up into more complex forms.
So lets start with the conditionals. if takes 3 arguments. It evaluates the first, and if that's true, if returns the second, and if the first argument is false it returns the third.
(if #t "some value" "some other value") ; => "some value"
(if #f "some value" "some other value") ; => "some other value"
(if (<= 1 0) "done" "go again") ; => "go again"
cond would work too - you can read the racket introduction to conditionals here: http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29
You can define functions in two different ways. You're using the anonymous function approach, which is fine, but you don't need a lambda in this case, so the simpler syntax is:
(define (function-name arguments) result)
For example:
(define (previous-number n)
(- n 1))
(previous-number 3) ; => 2
Using a lambda like you have achieves the same thing, using different syntax (don't worry about any other differences for now):
(define previous-number* (lambda (n) (- n 1)))
(previous-number* 3) ; => 2
By the way - that '*' is just another character in that name, nothing special (see http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Identifiers%29). A '!' at the end of a function name often means that that function has side effects, but n! is a fine name for your function in this case.
So lets go back to your original question and put the function definition and conditional together. We'll use the "recurrence relation" from the wiki definition because it makes for a nice recursive function: If n is less than 1, then the factorial is 1. Otherwise, the factorial is n times the factorial of one less than n. In code, that looks like:
(define (n! n)
(if (<= n 1) ; If n is less than 1,
1 ; then the factorial is 1
(* n (n! (- n 1))))) ; Otherwise, the factorial is n times the factorial of one less than n.
That last clause is a little denser than I'd like, so lets just work though it down for n = 2:
(define n 2)
(* n (n! (- n 1)))
; =>
(* 2 (n! (- 2 1)))
(* 2 (n! 1))
(* 2 1)
2
Also, if you're using Racket, it's really easy to confirm that it's working as we expect:
(check-expect (n! 0) 1)
(check-expect (n! 1) 1)
(check-expect (n! 20) 2432902008176640000)

Function definition in Haskell

I'm beginning to learn Haskell with "Learn You a Haskell for Great Good!" and I've made a strange mistake, which I can't find the reason for.
Here is the code I typed:
let xs = [if x < 3 then "bang" else "boom" | x <- xs]
And the the text of the error in GHCi:
No instance for (Num [Char])
arising from the literal `3'
Possible fix: add an instance declaration for (Num [Char])
In the second argument of `(<)', namely `(3)'
In the expression: x < (3)
In the expression: if x < (3) then "bang" else "boom"
But when I type:
let boom xs = [if x < 3 then "bang" else "boom" | x <- xs]
which is the example of the book, I don't have any problem.
Could someone explain my mistake?
Your definition of xs is recursive, that is you're using xs inside its own definition. I don't think that's what you intended.
Since you're using "bang" and "boom" inside the list comprehensions, Haskell knows that xs must be a list of strings (because xs is equal to the result of the list comprehension). Further you say that x is an element of xs (x <- xs), so x must be a String (a.k.a. [Char]). However you do x < 3, which implies that x is a number. The error message means "a String is not a number".
Try to give the expression a type.
xs = [if x < 3 then "bang" else "boom" | x <- xs]
So xs is a list, we don't know yet what type its elements have, so let's look at that next. The list elements are
if x < 3 then "bang" else "boom"
which is an expression of type String (aka [Char]).
So xs :: [String]. Since the x from the expression describing the list elements is taken from the list xs itself, it is a String too, and is used in the comparison
if x < 3
Now, 3 is an integer literal, thus it is polymorphic and has type
3 :: Num a => a
So from the expression x < 3, we have
a Num constraint from the literal,
the type String from the fact that x is drawn from a list of Strings.
Thus we need a Num instance for String to have a well-typed expression.
Usually, there is no Num instance for String (what would a useful one look like?), so you get a type error.
If xs is the argument of a function,
boom xs = [if x < 3 then "bang" else "boom" | x <- xs]
there is no reason why the type of x should be String, hence that works.
let xs = ...
means xs equals a list of "bang"s and/or "boom"s, but the condition states that those elements should be tested for <3, which is usually done with numbers, not strings.
let boom xs =...
equates the function 'boom' with the right hand side of the equation, where the parameter 'xs' is the list from which the elements to be tested for <3 are drawn.