What code is more readable / fast to make sure a binary digit is always zero in an input - elm

Variant 1
convertToBinary digitsList =
digitsList
|> List.take 4
|> setLastDigitToZero
|> numberFromDigits
setLastDigitToZero digitsList =
Array.fromList digitsList
|> Array.set (lastIndex digitsList) 0
|> Array.toList
lastIndex digitsList =
List.length digitsList - 1
vs
Variant 2
convertToBinary digitList =
digitList
|> List.take 3
|> List.reverse
|> List.append [ 1 ]
|> List.reverse
|> numberFromDigits
What do you think? And most importantly why?

It appears that you want to set the least significant digit in a 4 bit number to zero. You do this by passing in arrays of digits, using array operations to set a digit to zero, and then reassemble the number.
This is going to be slow no matter how you do it.
The dramatically much faster way is keeping the numbers as integers and using bitwise operations:
clearLeastSignificantBit : Int -> Int
clearLeastSignificantBit n = Bitwise.and n 0x0E -- 00001110 in binary
This way:
clearLeastSignificantBit 15 == 14 -- 1111 -> 1110
clearLeastSignificantBit 10 == 10 -- 1010 -> 1010
clearLeastSignificantBit 3 == 2 -- 0011 -> 0010
Since programmers are generally familiar with bitwise operations, this is quite readable.

Related

What is the remainder operator for Elm

I have this function
result =
add 1 2 |> \a -> a % 2 == 0)
and I am getting this error
Elm does not use (%) as the remainder operator
When I look at the docs I see I can use modBy, so I tried this.
result =
add 1 2 |> (\a -> a modBy 2 == 0)
But that gives me the following error.
This function cannot handle the argument sent through the (|>) pipe:
The % operator was removed in 0.19 to reduce the confusion between rem and mod.
modBy and remainderBy are regular functions. You use them like:
result = add 1 2 |> (\a -> modBy 2 a == 0)
or, if you prefer a functional composition variant of the code:
result = add 1 2 |> modBy 2 >> (==) 0
As a historical note, there used to be a way to call functions infix using backticks notation:
a `modBy` 2
but this was removed in 0.18

Where the Hamming Distance Constants Came From

The function:
function popcount (x, n) {
if (n !== undefined) {
x &= (1 << n) - 1
}
x -= x >> 1 & 0x55555555
x = (x & 0x33333333) + (x >> 2 & 0x33333333)
x = x + (x >> 4) & 0x0f0f0f0f
x += x >> 8
x += x >> 16
return x & 0x7f
}
Is for calculating Hamming Weight. I am wondering where these constants come from and generally how this method was discovered. Wondering if anyone knows the resource that describes it.
There masks select the even numbered k-bit parts, k=1 gives 0x55555555, k=2 gives 0x33333333, k=4 gives 0x0f0f0f0f.
In binary the masks look like:
0x55555555 = 01010101010101010101010101010101
0x33333333 = 00110011001100110011001100110011
0x0f0f0f0f = 00001111000011110000111100001111
They are also the result of 0xffffffff / 3, 0xffffffff / 5 and 0xffffffff / 17 but this arithmetic insight is probably not useful in this context.
Overall this method of computing the Hamming weight has the form of a tree where first adjacent bits are summed into a 2-bit number, then adjacent 2-bit numbers are summed into 4-bit numbers, and so on.
All the steps could have this form:
x = (x & m[k]) + ((x >> k) & m[k])
where m[k] is a mask selecting the even-numbered k-bit parts.
But many steps have short-cuts available for them. For example, to sum adjacent bits, there are only 4 cases to consider:
00 -> 00
01 -> 01
10 -> 01
11 -> 10
This could be done by extracting both bits and summing them, but x -= x >> 1 & 0x55555555 also works. This subtracts the top bit from the 2-bit part, so
00 -> 00 - 0 = 00
01 -> 01 - 0 = 01
10 -> 10 - 1 = 01
11 -> 11 - 1 = 10
Maybe this could be discovered through "cleverness and insight", whatever those are.
In the step x = (x + (x >> 4)) & 0x0f0f0f0f (extra parentheses added for clarity), a couple of properties are used. The results from the previous steps are the Hamming weights of 4-bit strings stored in 4 bits each, so they are at most 0100. That means two of them can be added in-place without carrying into the next higher part, because their sum will be at most 1000 which still fits. So instead of masking twice before the sum, it is enough to mask once after the sum, this mask effectively zero-extends the even numbered 4-bit parts into 8-bit parts. This could be discovered by considering the maximum values at each step.
The step x += x >> 8 has similar reasoning but it works out even better, even masking after the sum is not needed, this leaves some "stray bits" in the second byte from the bottom and in the top byte, but that is not damaging to the next step: the >> 16 throws away the second byte from the bottom, in the end all the stray bits are removed with x & 0x7f.

How do you operate on dependent pairs in a proof?

This is a follow up to this question. Thanks to Kwartz I now have a state of the proposition if b divides a then b divides a * c for any integer c, namely:
alsoDividesMultiples : (a, b, c : Integer) ->
DivisibleBy a b ->
DivisibleBy (a * c) b
Now, the goal has been to prove that statement. I realized that I do not understand how to operate on dependent pairs. I tried a simpler problem, which was show that every number is divisible by 1. After a shameful amount of thought on it, I thought I had come up with a solution:
-- All numbers are divisible by 1.
DivisibleBy a 1 = let n = a in
(n : Integer ** a = 1 * n)
This compiles, but I was had doubts it was valid. To verify that I was wrong, it changed it slightly to:
-- All numbers are divisible by 1.
DivisibleBy a 1 = let n = a in
(n : Integer ** a = 2 * n)
This also compiles, which means my "English" interpretation is certainly incorrect, for I would interpret this as "All numbers are divisible by one since every number is two times another integer". Thus, I am not entirely sure what I am demonstrating with that statement. So, I went back and tried a more conventional way of stating the problem:
oneDividesAll : (a : Integer) ->
(DivisibleBy a 1)
oneDividesAll a = ?sorry
For the implementation of oneDividesAll I am not really sure how to "inject" the fact that (n = a). For example, I would write (in English) this proof as:
We wish to show that 1 | a. If so, it follows that a = 1 * n for some n. Let n = a, then a = a * 1, which is true by identity.
I am not sure how to really say: "Consider when n = a". From my understanding, the rewrite tactic requires a proof that n = a.
I tried adapting my fallacious proof:
oneDividesAll : (a : Integer) ->
(DivisibleBy a 1)
oneDividesAll a = let n = a in (n : Integer ** a = b * n)
But this gives:
|
12 | oneDividesAll a = let n = a in (n : Integer ** a = b * n)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When checking right hand side of oneDividesAll with expected type
DivisibleBy a 1
Type mismatch between
Type (Type of DPair a P)
and
(n : Integer ** a = prim__mulBigInt 1 n) (Expected type)
Any help/hints would be appreciated.
First off, if you want to prove properties on number, you should use Nat (or other inductive types). Integer uses primitives that the argument can't argue further than prim__mulBigInt : Integer -> Integer -> Integer; that you pass two Integer to get one. The compiler doesn't know anything how the resulting Integer looks like, so it cannot prove stuff about it.
So I'll go along with Nat:
DivisibleBy : Nat -> Nat -> Type
DivisibleBy a b = (n : Nat ** a = b * n)
Again, this is a proposition, not a proof. DivisibleBy 6 0 is a valid type, but you won't find a proof : Divisible 6 0. So you were right with
oneDividesAll : (a : Nat) ->
(DivisibleBy a 1)
oneDividesAll a = ?sorry
With that, you could generate proofs of the form oneDividesAll a : DivisibleBy a 1. So, what comes into the hole ?sorry? :t sorry gives us sorry : (n : Nat ** a = plus n 0) (which is just DivisibleBy a 1 resolved as far as Idris can). You got confused on the right part of the pair: x = y is a type, but now we need a value – that's what's your last error cryptic error message hints at). = has only one constructor, Refl : x = x. So we need to get both sides of the equality to the same value, so the result looks something like (n ** Refl).
As you thought, we need to set n to a:
oneDividesAll a = (a ** ?hole)
For the needed rewrite tactic we check out :search plus a 0 = a, and see plusZeroRightNeutral has the right type.
oneDividesAll a = (a ** rewrite plusZeroRightNeutral a in ?hole)
Now :t hole gives us hole : a = a so we can just auto-complete to Refl:
oneDividesAll a = (a ** rewrite plusZeroRightNeutral a in Refl)
A good tutorial on theorem proving (where it's also explained why plus a Z does not reduce) is in the Idris Doc.

What does this function do , Haskell

I need an algorithm that converts bin to dec
I found the following code in the Internet , but I just do not know , what some variables mean:
bin2dec :: [Int] -> Int
bin2dec n = foldl (\a x->2*a+x) 0 n
I already know foldl
But what means (\a x->2*a+x) 0 n
I do not know what \a x -> 2*a+x means and also " 0 n"
Could anyone please explain me how this function works ?
Thanks
foldl :: (a -> b -> a) -> a -> [b] -> a
So basically a is first 0 and then the value that is carried throughout the fold. n is the list you pass into bin2dec and 0 is the object you start your fold on.
\a x -> 2 * a + x is a lamda function. It takes two variables, a and x and returns the value given on the right side of the arrow.

Unrestricted grammar

What does this general grammar do?
S -> LR
L -> L0Y
L -> LX
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
L -> epsilon
R -> epsilon
the start symbol is S. I tried to generate string from this grammar and I got every binary numbers. but I think it does something specific.
S -> LR
L -> L0Y
L -> LX
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
L -> epsilon
R -> epsilon
terminals: 0,1
start: S
Let's split the grammar:
S -> LR
L -> L0Y
L -> LX
This will generate a string in the form L, string of X and 0Y, R.
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
Treat X and Y as acting on the binary string: X will propagate to the right, then change a 0 to 1 and all subsequent 1s to 0s. In effect, a single X increments the binary number without changing its string length (or gets stuck).
A leading Y will rewrite the string of all 1s to all 0s (or gets stuck).
Treat the rules for L as the possible actions on the right part of the string. L => L0Y will reset the string from all ones to all zeroes and increase its length by one. L => LX will increment any other number, but fails if the value is at the maximum.
These two actions together are sufficient to generate (inefficiently) all strings of zeroes and ones (including the empty string).
L -> epsilon
R -> epsilon
will only clean up the sentinels.
one possible description of the language within four words:
set of all strings