Iteratively declaring distinct variables - unique

This question is strongly related to this and this question.
The distinct function of Z3
(declare-const a S)
(declare-const b S)
(assert (distinct a b))
allows constraining sets of variables (here a and b) such that all variables in the set must take different values.
My question is: is it also possible to force a variable to take a unique value without explicitly referring to the set of variables from which it should be distinct? Something like
(declare-unique-const a S)
(declare-unique-const b S)
(declare-unique-const c S)
This would be nice in situations where you declare new variables in an iterative process, for example, during program verification.
If it is not possible, I guess one has to keep track of all distinct variables and use that set to emit appropriate distinct (newvar, oldvar1, ..., oldvarn)) constraints.

We can define an auxiliary fresh function f from S to Int, and assert
f(a_1) = 1
f(a_1) = 2
f(a_3) = 3
...
f(a_n) = n
Then, a_1, ..., a_n must be different from each other.
If we want to say that b is also different from all a_is. We just assert
f(b) = n+1
In this approach, we only have to track the counter.

Related

Randomely creating a boolean function of N boolean variables

I want to write a program for randomely creating a function that receives as an input N binary values, and maps them into one binary value. The naïve approach would be to create all 2^(2^N) such functions, represented as truth tables, and choose one at random - but this is impractical for large N. In addition, as representing the chosen function in truth table is memory inefficient, it would be desirable to represent it as a formula y = f(x1,x2,...,xN).
Thanks!
Assume we have an array x[1..n] of Boolean values. The idea is to create an auxiliary Bernoulli Distribution b and apply and or or in sequence with a probability of 50%.
1. result:= true.
b := Bernoulli(0.5).
2. For i = 1 To n Do:
3. If next(b)
Then result := and(result, x[i])
Else result := or(result, x[i])
4. Return result

Haskell 2014.0.0: Two 'Could not deduce' errors occur when executing simple function

I want to program a function 'kans' (which calculates the chance of a repetition code of length n being correctly decoded) the following way:
fac 0 = 1
fac n = n * fac (n-1)
comb n r = ceiling (fac n / ((fac (n - r))*(fac r)))
kans 0 = 1
kans n = sum [ (comb (n+1) i) * 0.01^i * 0.99^(n+1-i) | i <- [0..(div n 2)]]
Now, calling 'kans 2' in GHCi gives the following error message: http://i.imgur.com/wEZRXgu.jpg
The functions 'fac' and 'comb' function normally. I even get an error message when I call 'kans 0', which I defined seperately.
I would greatly appreciate your help.
The error messages both contain telling parts of the form
Could not deduce [...]
from the context (Integral a, Fractional a)
This says that you are trying to use a single type as both a member of the class Integral and as a member of the class Fractional. There are no such types in Haskell: The standard numerical types all belong to exactly one of them. And you are using operations that require one or the other:
/ is "floating point" or "field" division, and only works with Fractional.
div is "integer division", and so works only with Integral.
the second argument of ^ must be Integral.
What you probably should do is to decide exactly which of your variables and results are integers (and thus in the Integral class), and which are floating-point (and thus in the Fractional class.) Then use the fromIntegral function to convert from the former to the latter whenever necessary. You will need to do this conversion in at least one of your functions.
On mathematical principle I recommend you do it in kans, and change comb to be purely integral by using div instead of /.
As #Mephy suggests, you probably should write type signatures for your functions, this helps make error messages clearer. However Num won't be enough here. For kans you can use either of
kans :: Integer -> Double
kans :: (Integral a, Fractional b) => a -> b
The latter is more general, but the former is likely to be the two specific types you'll actually use.
short dirty answer:
because both fac and comb always return Integers and only accept Integers, use this code:
fac 0 = 1
fac n = n * fac (n-1)
comb n r =fac n `div` ((fac (n - r))*(fac r))
kans 0 = 1
kans n = sum [ fromIntegral (comb (n+1) i) * 0.01^i * 0.99^(n+1-i) | i <- [0..(div n 2)]]
actual explanation:
looking at your error messages, GHC complains about ambiguity.
let's say you try to run this piece of code:
x = show (read "abc")
GHC will complain that it can't compute read "abc" because it doesn't have enough information to determine which definition of read to use (there are multiple definitions ; you might want to read about type classes, or maybe you already did. for example, one of type String -> Int which parses Integers and one of type String -> Float etc.). this is called ambiguity, because the result type of read "abc" is ambiguous.
in Haskell, when using arithmetic operators (which like read usually have multiple definitions in the same way) there is ambiguity all the time, so when there is ambiguity GHC checks if the types Integer or Float can be plugged in without problems, and if they do, then it changes the types to them, resolving the ambiguity. otherwise, it complains about the ambiguity. this is called defaulting.
the problem with your code is that because of the use of ceiling and / the types require instances of Fractional and RealFrac while also requiring instances of Integral for the same type variables, but no type is instance of both at once, so GHC complains about ambiguity.
the way to fix this would be to notice that comb would only work on whole numbers, and that (fac n / ((fac (n - r))*(fac r))) is always a whole number. the ceiling is redundant.
then we should replace / in comb's definition by \div`` to express that only whole numbers will be the output.
the last thing to do is to replace comb (n+1) i with fromIntegral (comb (n+1) i) (fromIntegral is a function which casts whole numbers to arbitrary types) because otherwise the types would mismach again - adding this allowes us to separate the type of comb (n+1) i (which is a whole number) from the type of 0.01^i which is of course a floating-point number.
this solves all problems and results in the code I wrote above in the "short dirty answer" section.

Does Haskell have variadic functions/tuples?

The uncurry function only works for functions taking two arguments:
uncurry :: (a -> b -> c) -> (a, b) -> c
If I want to uncurry functions with an arbitrary number of arguments, I could just write separate functions:
uncurry2 f (a, b) = f a b
uncurry3 f (a, b, c) = f a b c
uncurry4 f (a, b, c, d) = f a b c d
uncurry5 f (a, b, c, d, e) = f a b c d e
But this gets tedious quickly. Is there any way to generalize this, so I only have to write one function?
Try uncurryN from the tuple package. Like all forms of overloading, it's implemented using type classes. In this case by manually spelling out the instances up to 15-tuples, which should be more than enough.
Variadic functions are also possible using type classes. One example of this is Text.Printf. In this case, it's done by structural induction on the function type. Simplified, it works like this:
class Foo t
instance Foo (IO a)
instance Foo b => Foo (a -> b)
foo :: Foo
It shouldn't be hard to see that foo can be instantiated to the types IO a, a -> IO b, a -> b -> IO c and so on. QuickCheck also uses this technique.
Structural induction won't work on tuples, though, as an n-tuple is completely unrelated to a n+1-tuple, so that's why the instances have to be spelled out manually.
Finding ways to fake this sort of thing using overwrought type system tricks is one of my hobbies, so trust me when I say that the result is pretty ugly. In particular, note that tuples aren't defined recursively, so there's no real way to abstract over them directly; as far as Haskell's type system is concerned, every tuple size is completely distinct.
Any viable approach for working with tuples directly will therefore require code generation--either using TH, or an external tool as with the tuple package.
To fake it without using generated code, you have to first resort to using recursive definitions--typically right-nested pairs with a "nil" value to mark the end, either (,) and () or something equivalent to them. You may notice that this is similar to the definition of lists in terms of (:) and []--and in fact, recursively defined faux-tuples of this sort can be seen as either type-level data structures (a list of types) or as heterogeneous lists (e.g., HList works this way).
The downsides include, but are not limited to, the fact that actually using things built this way can be more awkward than it's worth, the code to implement the type system tricks is usually baffling and completely non-portable, and the end result is not necessarily equivalent anyway--there are multiple nontrivial differences between (a, (b, (c, ()))) and (a, b, c), for instance.
If you want to see how horrible it becomes you can look at the stuff I have on GitHub, particularly the bits here.
There is no straightforward way to write a single definition of uncurry that will work for different numbers of arguments.
However, it is possible to use Template Haskell to generate the many different variants that you would otherwise have to write by hand.

What is the difference between Set ( = ) and SetDelayed ( := )?

This discussion came up in a previous question and I'm interested in knowing the difference between the two. Illustration with an example would be nice.
Basic Example
Here is an example from Leonid Shifrin's book Mathematica programming: an advanced introduction
It is an excellent resource for this kind of question. See: (1) (2)
ClearAll[a, b]
a = RandomInteger[{1, 10}];
b := RandomInteger[{1, 10}]
Table[a, {5}]
{4, 4, 4, 4, 4}
Table[b, {5}]
{10, 5, 2, 1, 3}
Complicated Example
The example above may give the impression that once a definition for a symbol is created using Set, its value is fixed, and does not change. This is not so.
f = ... assigns to f an expression as it evaluates at the time of assignment. If symbols remain in that evaluated expression, and later their values change, so does the apparent value of f.
ClearAll[f, x]
f = 2 x;
f
2 x
x = 7;
f
14
x = 3;
f
6
It is useful to keep in mind how the rules are stored internally. For symbols assigned a value as symbol = expression, the rules are stored in OwnValues. Usually (but not always), OwnValues contains just one rule. In this particular case,
In[84]:= OwnValues[f]
Out[84]= {HoldPattern[f] :> 2 x}
The important part for us now is the r.h.s., which contains x as a symbol. What really matters for evaluation is this form - the way the rules are stored internally. As long as x did not have a value at the moment of assignment, both Set and SetDelayed produce (create) the same rule above in the global rule base, and that is all that matters. They are, therefore, equivalent in this context.
The end result is a symbol f that has a function-like behavior, since its computed value depends on the current value of x. This is not a true function however, since it does not have any parameters, and triggers only changes of the symbol x. Generally, the use of such constructs should be discouraged, since implicit dependencies on global symbols (variables) are just as bad in Mathematica as they are in other languages - they make the code harder to understand and bugs subtler and easier to overlook. Somewhat related discussion can be found here.
Set used for functions
Set can be used for functions, and sometimes it needs to be. Let me give you an example. Here Mathematica symbolically solves the Sum, and then assigns that to aF(x), which is then used for the plot.
ClearAll[aF, x]
aF[x_] = Sum[x^n Fibonacci[n], {n, 1, \[Infinity]}];
DiscretePlot[aF[x], {x, 1, 50}]
If on the other hand you try to use SetDelayed then you pass each value to be plotted to the Sum function. Not only will this be much slower, but at least on Mathematica 7, it fails entirely.
ClearAll[aF, x]
aF[x_] := Sum[x^n Fibonacci[n], {n, 1, \[Infinity]}];
DiscretePlot[aF[x], {x, 1, 50}]
If one wants to make sure that possible global values for formal parameters (x here) do not interfere and are ignored during the process of defining a new function, an alternative to Clear is to wrap Block around the definition:
ClearAll[aF, x];
x = 1;
Block[{x}, aF[x_] = Sum[x^n Fibonacci[n], {n, 1, \[Infinity]}]];
A look at the function's definition confirms that we get what we wanted:
?aF
Global`aF
aF[x_]=-(x/(-1+x+x^2))
In[1]:= Attributes[Set]
Out[1]= {HoldFirst, Protected, SequenceHold}
In[2]:= Attributes[SetDelayed]
Out[2]= {HoldAll, Protected, SequenceHold}
As you can see by their attributes, both functions hold their first argument (the symbol to which you are assigning), but they differ in that SetDelayed also holds its second argument, while Set does not. This means that Set will evaluate the expression to the right of = at the time the assignment is made. SetDelayed does not evaluate the expression to the right of the := until the variable is actually used.
What's happening is more clear if the right hand side of the assignment has a side effect (e.g. Print[]):
In[3]:= x = (Print["right hand side of Set"]; 3)
x
x
x
During evaluation of In[3]:= right hand side of Set
Out[3]= 3
Out[4]= 3
Out[5]= 3
Out[6]= 3
In[7]:= x := (Print["right hand side of SetDelayed"]; 3)
x
x
x
During evaluation of In[7]:= right hand side of SetDelayed
Out[8]= 3
During evaluation of In[7]:= right hand side of SetDelayed
Out[9]= 3
During evaluation of In[7]:= right hand side of SetDelayed
Out[10]= 3
:= is for defining functions and = is for setting a value, basically.
ie := will evaluate when its read, = will be evaluated when it is set.
think about:
x = 2
y = x
z := x
x = 4
Now, z is 4 if evaluated while y is still 2

Uses for Haskell id function

Which are the uses for id function in Haskell?
It's useful as an argument to higher order functions (functions which take functions as arguments), where you want some particular value left unchanged.
Example 1: Leave a value alone if it is in a Just, otherwise, return a default of 7.
Prelude Data.Maybe> :t maybe
maybe :: b -> (a -> b) -> Maybe a -> b
Prelude Data.Maybe> maybe 7 id (Just 2)
2
Example 2: building up a function via a fold:
Prelude Data.Maybe> :t foldr (.) id [(+2), (*7)]
:: (Num a) => a -> a
Prelude Data.Maybe> let f = foldr (.) id [(+2), (*7)]
Prelude Data.Maybe> f 7
51
We built a new function f by folding a list of functions together with (.), using id as the base case.
Example 3: the base case for functions as monoids (simplified).
instance Monoid (a -> a) where
mempty = id
f `mappend` g = (f . g)
Similar to our example with fold, functions can be treated as concatenable values, with id serving for the empty case, and (.) as append.
Example 4: a trivial hash function.
Data.HashTable> h <- new (==) id :: IO (HashTable Data.Int.Int32 Int)
Data.HashTable> insert h 7 2
Data.HashTable> Data.HashTable.lookup h 7
Just 2
Hashtables require a hashing function. But what if your key is already hashed? Then pass the id function, to fill in as your hashing method, with zero performance overhead.
If you manipulate numbers, particularly with addition and multiplication, you'll have noticed the usefulness of 0 and 1. Likewise, if you manipulate lists, the empty list turns out to be quite handy. Similarly, if you manipulate functions (very common in functional programming), you'll come to notice the same sort of usefulness of id.
In functional languages, functions are first class values
that you can pass as a parameter.
So one of the most common uses of id comes up when
you pass a function as a
parameter to another function to tell it what to do.
One of the choices of what to do is likely to be
"just leave it alone" - in that case, you pass id
as the parameter.
Suppose you're searching for some kind of solution to a puzzle where you make a move at each turn. You start with a candidate position pos. At each stage there is a list of possible transformations you could make to pos (eg. sliding a piece in the puzzle). In a functional language it's natural to represent transformations as functions so now you can make a list of moves using a list of functions. If "doing nothing" is a legal move in this puzzle, then you would represent that with id. If you didn't do that then you'd need to handle "doing nothing" as a special case that works differently from "doing something". By using id you can handle all cases uniformly in a single list.
This is probably the reason why almost all uses of id exist. To handle "doing nothing" uniformly with "doing something".
For a different sort of answer:
I'll often do this when chaining multiple functions via composition:
foo = id
. bar
. baz
. etc
over
foo = bar
. baz
. etc
It keeps things easier to edit. One can do similar things with other 'zero' elements, such as
foo = return
>>= bar
>>= baz
foos = []
++ bars
++ bazs
Since we are finding nice applications of id. Here, have a palindrome :)
import Control.Applicative
pal :: [a] -> [a]
pal = (++) <$> id <*> reverse
Imagine you are a computer, i.e. you can execute a sequence of steps. Then if I want you to stay in your current state, but I always have to give you an instruction (I cannot just mute and let the time pass), what instruction do I give you? Id is the function created for that, for returning the argument unchanged (in the case of the previous computer the argument would be its state) and for having a name for it. That necessity appears only when you have high order functions, when you operate with functions without considering what's inside them, that forces you to represent symbolically even the "do nothing" implementation. Analogously 0 seen as a quantity of something, is a symbol for the absence of quantity. Actually in Algebra both 0 and id are considered the neutral elements of the operations + and ∘ (function composition) respectively, or more formally:
for all x of type number:
0 + x = x
x + 0 = x
for all f of type function:
id ∘ f = f
f ∘ id = f
I can also help improve your golf score. Instead of using
($)
you can save a single character by using id.
e.g.
zipWith id [(+1), succ] [2,3,4]
An interesting, more than useful result.
Whenever you need to have a function somewhere, but want to do more than just hold its place (with 'undefined' as an example).
It's also useful, as (soon-to-be) Dr. Stewart mentioned above, for when you need to pass a function as an argument to another function:
join = (>>= id)
or as the result of a function:
let f = id in f 10
(presumably, you will edit the above function later to do something more "interesting"... ;)
As others have mentioned, id is a wonderful place-holder for when you need a function somewhere.