How to convert a list of binary to char? - erlang

I would like to convert a list of zeros and ones to a char.
example :
bitToChar([1,0,0,0,1,0,1]) = $Q
Thanks.

Another way to do it is to use a bit string comprehension:
X = [1,0,0,0,1,0,1],
<<C:7>> = << <<Bit:1>> || Bit <- lists:reverse(X) >>,
$Q == C.
That is, pick one element at a time from the list, and use each element as a bit in the binary being built, and finally extract a seven-bit number into the variable C.

You can add $0 to each of them (to make it a string with $0s and $1s), reverse the list, and use list_to_integer/2 with base 2:
1> list_to_integer(lists:reverse([N + $0 || N <- [1,0,0,0,1,0,1]]), 2) == $Q.
true
You can also use lists:foldl. The code is slightly longer but it doesn't use list_to_binary:
1> element(2, lists:foldl(fun(Digit, {Mul, Acc}) -> {Mul * 2, Acc + Digit * Mul} end, {1, 0}, Xs)) == $Q. true
This is basically equivalent to doing: 1 * 1 + 0 * 2 + 0 * 4 + 0 * 8 + 1 * 16 + 0 * 32 + 1 * 64.

$Q = lists:foldr(fun(X,Acc) -> X + (Acc bsl 1) end, 0,[1,0,0,0,1,0,1]).

Since $Q is integer value all you have to do is use in BitToChar conversion from binary based number to decimal based number.
Simplest conversion is:
to_decimal(X) ->
to_decimal(lists:reverse(X), 1, 0).
% you can validate that if H = 1 then add, if other not but I omitted this validation
to_decimal([H | T], Times, Acc) ->
to_decimal(T, 2 * Times, H * Times + Acc);
to_decimal([], _Times, Acc) -> Acc.
And then it will return integer.
In your case:
> $Q = 81.
81
> $Q == 81.
true

Related

how can I rewrite, and optimize, this EMA calculation in F#

this is an EMA calculation:
let EMA (period : int) (data : double[]) : double[] =
let multiplier = 2.0 / (double)(period + 1)
let output = Array.create data.Length System.Double.NaN
output.[period - 1] <- data.[0..period - 1] |> Seq.average
for i in seq {period .. (data.Length - 1)} do
output.[i] <- (data.[i] * multiplier) + (output.[i - 1] * (1. - multiplier))
output
you can test it with:
EMA 3 [|1.;3.;4.;7.;5.;6.;9.;8.|]
and it gives:
[|NaN;Nan;2.66.;4.83;4.91;5.45;7.22;7.61|]
my first question is regarding the loop at the end:
for i in seq {period .. (data.Length - 1)} do
output.[i] <- (data.[i] * multiplier) + (output.[i - 1] * (1. - multiplier))
can this be rewritten using a sequence operator?
my second question is: is there a fast F# implementation floating around? I couldn't find any.
Well, I don't know about floating around, but I did just write an EMA function yesterday. It looks like this:
let ema alpha vs =
(None, vs)
||> Array.scan (fun prev x ->
match prev with
| None -> Some(x)
| Some(s) -> Some(alpha*x + (1. - alpha)*s))
|> Array.choose id
My version looks all the way back, rather than only a number of periods, as your version. If you want that behaviour instead, you could replace the state of type float option in my version with a float[], or even implement it using the Array.windowed function.

Overflow of an int in f#

I am working on some homework and we are supposed to be making a combination function in F#. I have got the factorial function down, but it seems to overflow once I get a big number to use factorial on. (Let's say 20) I understand I can use an int64 or a float, but that would change all the inputs on the code. What data type should I use?
let rec Fact (a:int)=
if (a = 0) then 1 else a*Fact(a-1);;
let combo (n:int) (k:int)=
if (n = 0) then 0 else (Fact n)/((Fact k)*(Fact (n-k)));;
On the code right now, when I do combo 20 5;; it gives me 2147. Which is clearly the wrong answer. I looked at the factorial function and when I put 20 in there it gave me a big negative number. Any help would be much appreciated. Thanks in advance.
First of all, if you want to avoid surprises, you can open the Checked module at the top of your file. This will redefine the numerical operators so that they perform overflow checks - and you'll get an exception rather than unexpected number:
open Microsoft.FSharp.Core.Operators.Checked
As Fyodor points out in the comment, you cannot fit factorial of 20 in int and you need int64. However, your combo function then performs division which will make the result of combo 20 5 small enough to fit into int.
One option is to change Fact to use int64, but keep combo as a function that takes and returns integers - you'll need to convert them to int64 before calling Fact and then back to int after performing the division:
let rec Fact (a:int64) =
if (a = 0L) then 1L else a * Fact(a-1L)
let combo (n:int) (k:int) =
if (n = 0) then 0 else int (Fact (int64 n) / (Fact (int64 k) * Fact (int64 (n-k))))
Now you can call combo 20 5 and you'll get 15504 as the result.
EDIT: As noted by #pswg in the other answer, int64 is also quite limited and so you'll need BigInteger for larger factorials. However, the same method should work for you with BigInteger. You can keep the combo function as a function that returns int by converting back from BigInteger to int.
You simply won't be able to do that with an 32-bit integer (int). A 64-bit integer will get you up to 20!, but will fail at 21!. The numbers just get too big, too quickly. To go any further than that you'll need to use System.Numerics.BigInteger (abbreviated bigint in F#).
The parameter can probably stay as an int to be reasonable, but you need to return a bigint:
let rec Fact (n : int) =
if n = 0 then bigint.One else (bigint n) * Fact (n - 1)
Or to be a little more idiomatic:
let rec Fact = function | 0 -> bigint.One | n -> (bigint n) * Fact (n - 1)
And now, in your Combo function, you'll need to use these bigint's internally for all math (thankfully the integer division is all you need in this case).
let Combo (n : int) (k : int) =
if n = 0 then bigint.Zero else (Fact n) / ((Fact k) * (Fact (n - k)))
If you really wanted to make Combo return an int, you can do that conversion here:
let Combo (n : int) (k : int) =
if n = 0 then 0 else (Fact n) / ((Fact k) * (Fact (n - k))) |> int
Examples:
Combo 20 5 // --> 15504
Combo 99 5 // --> 71523144 (would break if you used int64)
Edit: By rethinking your implementation of Combo you can get some big performance improvements out of this. See this question on Math.SE for the basis of this implementation:
let ComboFast (n : int) (k : int) =
let rec Combo_r (n : int) = function
| 0 -> bigint.One
| k -> (bigint n) * (Combo_r (n - 1) (k - 1)) / (bigint k)
Combo_r n (if (2 * k) > n then n - k else k)
A quick benchmark showed this to be significantly faster than the Fact-based version above:
Function Avg. Time (ms)
Combo 99 5 30.12570
ComboFast 99 5 0.72364

how to compute the number of total constraints in smtlib2 files in api

I used the Z3_ast fs = Z3_parse_smtlib2_file(ctx,arg[1],0,0,0,0,0,0) to read file.
Additionally to add into the solver utilized the expr F = to_expr(ctx,fs) and then s.add(F).
My question is how can I get the number of total constraints in each instance?
I also tried the F.num_args(), however, it is giving wrong size in some instances.
Are there any ways to compute the total constraints?
Using Goal.size() may do what you want, after you add F to some goal. Here's a link to the Python API description, I'm sure you can find the equivalent in the C/C++ API: http://research.microsoft.com/en-us/um/redmond/projects/z3/z3.html#Goal-size
An expr F represents an abstract syntax tree, so F.num_args() returns the number of (one-step) children that F has, which is probably why what you've been trying doesn't always work. For example, suppose F = a + b, then F.num_args() = 2. But also, if F = a + b*c, then F.num_args() = 2 as well, where the children would be a and b*c (assuming usual order of operations). Thus, to compute the number of constraints (in case your definition is different than what Goal.size() yields), you can use a recursive method that traverses the tree.
I've included an example below highlighting all of these (z3py link here: http://rise4fun.com/Z3Py/It5E ).
For instance, my definition of constraint (or rather the complexity of an expression in some sense) might be the number of leaves or the depth of the expression. You can get as detailed as you want with this, e.g., counting different types of operands to fit whatever your definition of constraint might be, since it's not totally clear from your question. For instance, you might define a constraint as the number of equalities and/or inequalities appearing in an expression. This would probably need to be modified to work for formulas with quantifiers, arrays, or uninterpreted functions. Also note that Z3 may simplify things automatically (e.g., 1 - 1 gets simplified to 0 in the example below).
a, b, c = Reals('a b c')
F = a + b
print F.num_args() # 2
F = a + b * c
print F.num_args() # 2
print F.children() # [a,b*c]
g = Goal()
g.add(F == 0)
print g.size() # number of constraints = 1
g.add(Or(F == 0, F == 1, F == 2, F == 3))
print g.size() # number of constraints = 2
print g
g.add(And(F == 0, F == 1, F == 2, F == 3))
print g.size() # number of constraints = 6
print g
def count_constraints(c,d,f):
print 'depth: ' + str(d) + ' expr: ' + str(f)
if f.num_args() == 0:
return c + 1
else:
d += 1
for a in f.children():
c += count_constraints(0, d, a)
return c
exp = a + b * c + a + c * c
print count_constraints(0,0,exp)
exp = And(a == b, b == c, a == 0, c == 0, b == 1 - 1)
print count_constraints(0,0,exp)
q, r, s = Bools('q r s')
exp = And(q, r, s)
print count_constraints(0,0,exp)

how to convert a large number exprimed on several bytes?

If a number is exprimed on 4 bytes, from LSB to MSB, how to convert it in integer ?
example:
<<77,0,0,0>> shall give 77
but
<<0,1,0,0>> shall give 256
Let S = <<0,1,0,0>>,
<<L1,L2,L3,L4>> = S,
L = L1*1 + L2*256 + L3*65536 + L4*16777216,
But it's not elegant ...
The bit syntax in Erlang does this in a very straightforward way:
<<A:32/little>> = <<0,1,0,0>>,
A.
% A = 256
or as a function:
decode(<<Int:32/little>>) -> Int.
% decode(<<0,1,0,0>>) =:= 256.
EDIT (this is the correct answer, and sorry for discovering it late...)
> binary:decode_unsigned(<<0,1,0,0>>,little).
256
The easier way would be something like:
decode_my_binary( <<A,B,C,D>> ) ->
A + B*256 + C*65536 + D*16777216.
EDIT:
As per your edit, if you find this one not very elegant, you can try other approaches. Still I think the above is the correct way of doing it. You can write a recursive function (not tested, but you get the idea):
decode( B ) -> decode(binary_to_list(B), 0, 1).
decode( [], R, _ ) -> R;
decode( [H|T], R, F) ->
decode(T, R + H*F, F*256).
but this is clearly slower. Another possibility is to have the list of the binary digits and the list of multipliers and then fold it:
lists:sum(lists:zipwith( fun(X,Y) -> X*Y end,
binary_to_list(B), [ math:pow(256,X) || X <- [0,1,2,3] ])).
Or if you want a variable number of digits:
fun(Digits) ->
lists:sum(lists:zipwith( fun(X,Y) -> X*Y end,
binary_to_list(B), [ math:pow(256,X) || X <- lists:seq(0,Digits-1])).
where Digits tell you the digit number.

Type inference in pattern match over list

I'm stuck with trying to create a function that will do the following:
let p = [1, 2, 4, 2, 1]
let v = 8
then I want to go over the elements in a until I find the index i of the one where all elements up to and including i are greater or equal than v. So in this case it should return 4, because 1+2+4 < 8 and 1+2+4+2 > 8. So there 4th element, value of 2 puts the total over 8.
(some background: I want to do monte carlo, where I have a list of probabilies that add up to 1. Then I pass a random number between 0 and 1 to have it pick one of the possible future states. Simple example here with ints)
What I have so far is this:
let p = [1, 2, 4, 2, 1]
let pick (v:int) (l:int list) =
let rec sub (i:int) (acc:int) (l2:int list) =
match l2 with
| h::t -> if acc+h >= v then i else sub(i+1, acc+h, t)
| _ -> failwith "total list didn't amount to " + v
sub 0 0 l
pick 8 p
But it gives the following error on the bit sub(i+1, acc+h, t):
error FS0001: This expression was expected to have type
int
but here has type
int -> int list -> int
But I'm not passing the function sub itself, I'm calling it complete with arguments and brackets and all, so why doesn't it return int, the result of the function?
How do I make it return the result of the function?
Thanks in advance,
Gert-Jan
you give the 3-tuple (i+1,acc+h,t) where curried function is supposted to be:
| h::t -> if acc+h >= v then i else sub (i+1) (acc+h) t
Try this.
First, p will be understood as [(1, 2, 4, 2, 1);] which is an (int*int*int*int*int) list with only one element. p as an int list should be [1; 2; 4; 2; 1].
Second, sub(i+1, acc+h, t) in line 6 should be called in the curried form, not in the tuple form. The correction is sub (i+1) (acc+h) t.

Resources