Mathematical functions in functional programming - clojure

I have just started learning clojure.As it belongs to a category of functional programming,as a first step i am figuring out how it is different from imperative programming. So i have learnt from wikipedia and other sources some raw knowledge.So I am pretty confused with this line saying
There are functions in imperative programming and mathematical functions in functional programming .Here what do mathematical functions exactly mean?How is it different from functions.
Consider mathematically a function f(x)=X^2+X+1
In terms of object oreiented programming we write a function which accepts an argument x and returns the calculated value.I believe the same is the case with functional programming.Then what does it mean by
Treats computation as the evaluation of mathematical functions
and avoids changing-state and mutable data.
Thanks for help!!

By mathematical function it is meant a function that always returns the same value when called with the same inputs. The following, for example, is not a mathematical function:
a = 0
def f(x):
a += 1
return x + a
Because, of course, if you call it multiple times with the same x you will get back different values. This happens because f increments a, this is what is called side effect and is what should be avoided in functional programming.

This is a very broad question. You might want to read up on:
Programming Paradigms
Referential Transparency
In this case here, "mathematical functions" refers to the property of "not causing side-effects" e.g. printing to the display, changing variables or sending packets over the network. Functions in OO-languages do usually modify state (they change the values of the corresponding object instance), whereas in functional languages, they don't.
An example of a mathematical function (fullfills referential transparency, e.g. given the same input, it returns the same output):
def square(x):
return x * x
An example of two non-mathematical functions (__init__ and increment). These are still functions, but they are "changing" things e.g. the variable current_count):
class Counter:
def __init__(self):
self.current_count = 0
def increment():
self.current_count += 1

Related

CUDD C++ Interface for converting Booleans to BDDs and resulting set of minterms (to cutsets)

I'm working with (https://github.com/ivmai/cudd) with the goal of the following repetitive process:
(1) Input: (Coherent, non-decreasing) Boolean function expression
top = a_1a_2a_3...+ x_1x_2x_3... + z_1z_2z_3...). The Booleans I'm working with have
thousands of vars (ai...zj) and hundreds of terms.
(2) Processing: Convert Boolean to a BDD to simplify the calculation of the minterms, or mutually
exclusive cut-sets (as we call them in the Reliability world).
(3) Output: Take the set of m.e. minimal cutsets (minterms). Calculate the top event probability by
adding up all the minterms found in (2).
I've found a way to do this with a labor-intensive manual C interface to build the Boolean. I've also found how to do it with the excellent tulip-dd Py interface, but unable to make it scale as with cudd.
Now I'm hoping with the C++ interface to cudd I can get the best of both worlds (Am I asking for too much?) Namely, the convenience of say tulip-dd with the scalability of cudd. So here's some sample code. Where I'm failing is in step 3, printing out the minterms, which I used to be able to do in C. How do I do it with the C++ interface?! Please see comments in the code for my specific thoughts and attempts.
int main()
{
/*DdManager* gbm; /* Global BDD manager. I suppose we do not use this if we use the Cudd type below.*/
/* (1-2) Declare the vars and build the Boolean. Convert Boolean to BDD */
Cudd mgr(0, 0);
BDD a = mgr.bddVar();
BDD b = mgr.bddVar();
BDD c = mgr.bddVar();
BDD d = mgr.bddVar();
BDD e = mgr.bddVar();
BDD top = a*(b + c + d*e);
/* How to print out the equivalent to below, which prints out all minterms and their relevant vars in C.
But the mgr below has to be a *DManager ? If so, how to convert? */
Cudd_PrintDebug(mgr, BDD, 2, 4);
return 0
}
Thanks,
Gui
The CUDD C++ classes are very little more than a wrapper around the "DdManager*" and "DdNode*" data types. They make sure that you don't accidentally forget to Cudd_Ref(..) or Cudd_RecursiveDeref(...) *DD nodes that you are using.
As such, these classes have functions that you can use to access the underlying data types. So for instance, if you want to call the "Cudd_PrintDebug" function on the "top" BDD, then you can do that with:
Cudd_PrintDebug(mgr.getManager(), top.getNode(), 2, 4);
The modification to your code was minimal.
Note that when using a plain CUDD DdNode* that you obtain with the "getNode" function, you have to make sure manually that you don't introduce node count leaks. If you use the DdNodes in a "read only fashion", only store DdNode* that correspond to BDD objects that you also store, and make sure that the BDD objects always live longer than the DdNode* pointers, this does not happen, though.
I'm only mentioning this since at some point you may want to iterate through the cubes of a BDD. These are essentially not-guaranteed-to-be-minimal minterms. There are special iterators in CUDD for this. However, if you really want the minterms, this may not be right approach. There is other software using CUDD that comes with its own functions for enumerating the minterms.
As a final note (outside of the scope of StackOverflow), you wrote that "The Booleans I'm working with have thousands of vars (ai...zj) and hundreds of terms." - There is no guarantee that using BDDs with so many variables is the way to go here. But please try it out. Having thousands of variables is often problematic for BDD-based approaches. Your application may or may not be an exception to this observation. An alternative approach may be to encode the search problem for all minterms of your original expression as an incremental satisfiability (SAT) solving problem.

How to use chop with if in Mathematica?

Suppose we have a set of 2 functions with multiple common arguments (x,y,z), let f_i(x,y,z) be one of those functions. When these arguments are evaluated by specific real numbers, Mathematica provides a solution which contains a real part and a very small irreal number (which I think is a calculation error), for the two functions.
I would like to create a new function with the same arguments that, when evaluated, chooses only the real part of the result of the function whose real result satisfies a certain criteria (e.g. be between -1 and 0).
This final function should allow me to plot the real part that matches the criteria in terms of any of its variables and to create other new functions.
I have tried the Chop and If functions in multiple orders without any success. My problem is that the chop function operates directly on the unevaluated functions and thus, does not allow me to attain the mentioned objective.
f[x_, y_, z_] =If[-1 <= Chop[f_1[x, y, z]] <= 0,Chop[f_1[x, y, z]],Chop[f_2[x, y, z]]]
Thank you very much.

Monad: Why does Identity matter, what's going to happen if there's no such special member in a set?

I'm trying to learn the concept of monad, I'm watching this excellent video Brian Beckend trying to explain what is monad.
When he talks about monoid, it's a collection of types, it has a rule of composition, and this composition has to obey 2 rules:
associative: x # (y # z ) = (x # y) # z
a special member in the collection: x # id = x and id # x = x
I'm using # symbol representing composition. id means the special member.
The second point is what I'm trying to understand. why does this matter ? what if there's no such special member ?
When I learn new concept, I always try to relate these abstract concept to some other concrete things, so that I can fully understand and learn them by heart.
So what I'm trying to relate monad and monoid to is lego. So all the building blocks in a lego set forms a collection. and the composition rule is composite them into new shape of building blocks. and it's obvious the composition obey the first rule: associative. But there's no special building block which can composite with other building block and get the same back. So it fails to obey the second rule.
But lego is still highly composable. What has been missing or lack when lego fails to obey the second rule ? What is the consequence ?
Or put it this way, comparing to other monoid which obey all those rules. What feature does other monoid has but lego doesn't ?
A monoid without an identity element is called a semigroup and its still a fine and useful construct. It just gives us something different. Consider, for example, a fold on a list. We can do this by mapping every element of a list to a monoid and then composing them all. But if you only have a semigroup, you can't fold on a possibly empty list.
Consider another example -- the integers greater than zero, versus the integers greater than or equal to zero. In the latter case we have a monoid, since zero is literally our zero element. So I can solve for example, the equation "5 + x = 5". In the former case, with a semigroup, I can't solve that equation. Or I can say "you have no apples, I then give you five apples, how many do you have?" In a world without zero, we have to assume everyone starts with some apples to begin with! So, for the same reasons having a zero lying around is important with numbers, it is handy to have a "generalized zero" hanging around with more abstract algebraic structures.
(Note this doesn't mean one or the other is "better" -- just that they are different, and the extra structure, when available, can come in handy. Also note that there is a universal way to turn a semigroup into a monoid by adding a zero element, so since all semigroup results lift into the 'completed' results on monoids, it tends to be more convenient, typically, to just treat things in terms of the latter.)
The empty Lego could be considered as id but then you will have to accept that empty space is Lego. But yes if you don't want id like #sclv wrote, it would be a semigroup.

Can I check whether a variable has deterministic value by C++ API

I noticed that Z3 can do allsmt from some paper. In my project, I have to search for deterministic variables in a SMT formula. By deterministic I mean the variable can only take one int value to make the formula satisfiable. Is there a c++/c API function which can do this task?
The best I can do so far is to call the solver.check() function many times for the negation of each variable I am interested in. Is there a faster way to do this by using the API?
Basically, I want to do allsmt and predicate abstraction/projection.
There is no specialized API for checking if all models of a given variable have to agree on the same value. You can implement more or less efficient algorithms on top of Z3 to solve this question.
Here is a possible algorithm:
Get a model M from Z3.
For the variables you are interested in assert: Not (And([(M.eval(x) == x) for x in Vars]))
Recheck satisfiability. If the new state is unsatisfiable, then the remaining variales in Vars must have the same value. Otherwise, remove variables from Vars that evaluate to a new value different from the old M.eval(x), and repeat (2) until Vars is either empty or the context is unsatisfiable.

How does boost::uBLAS handle nested products of matrices?

I read an article about the optimisation of nested product of matrices, using dynamic programming, and I wanted to see how it is implemented in boost::uBLAS.
I'm not sure I understood the documentation (they talk about it at the very end of the page), but it seems they handle this problem. When you write R = prod(A, prod(B,C));, the library computes A x (B x C) or (A x B) x C depending on the sizes of A, B and C.
How can it be achieved ? How can the library "move the brackets" ? When writing such a code line, I thought the arguments of prod would be evaluated, and then the function would be run.
The FAQ mentions the notion of expression templates. Is it linked ?
Yes, expression templates (which you may find under the name "expression trees") are involved.
Basically, prod doesn't return the result, but a wrapper object holding the operation (matrix multiply) and pointers to the two inputs. If prod is called with such a wrapper as input, it can apply reordering optimizations.
However, from my reading of that page, no such optimization is applied (it says it honors bracketing structure).