It seems that, as w/ Inductive and Fixpoint, you can mutually define Function's w/ with. Can you give the syntax and/or an example of this? I couldn't find anything anywhere. I suppose it's the same as for Fixpoint
(found nothing on this either). A non-working (but half-compiling -- the 2 last lines highlight in red) example:
Variable ARG:Type.
Variable phy inf phyinf: ARG.
Function Phy (x:ARG): ARG := match x with Inf x => phyinf | _ => phy end
with Inf (x:ARG): ARG := match x with Phy x => phyinf | _ => inf end. (*Error: Unknown constructor: Inf.*)
Alright, I think I finally understood your question.
There is indeed a way to mutually define several Fixpoint. It is (lightly) documented in the variant section here.
Similarly, there is a way to mutually define several Inductive types (documented here).
And there is a way to mutually define several Function. Note however the remark that the manual makes about this feature:
The Function construction enjoys also the with extension to define mutually recursive definitions. However, this feature does not work for non structural recursive functions.
The error that you are getting in your half-working example is not about syntax though, neither is it related to the Function ... with feature. The error is that you can only use pattern-matching on inductive types and branches must start with a constructor. In your example, ARG is not an inductive type and Inf is not a constructor. I can't really "correct" your example as I don't really see what you were trying to express. Was this example made just for this question? In this case, you stripped it down to too little.
PS: I wonder if somehow, you were trying to do induction-recursion (definining at the same time a recursive function and an inductive type). If this were the case, then no luck: Coq does not have this feature yet.
Related
Is there any substantial difference between operators and methods?
The only difference I see is the way the are called, do they have other differences?
For example in Python concatenation, slicing, indexing are defined as operators, while (referring to strings) upper(), replace(), strip() and so on are methods.
If I understand question currectly...
In nutshell, everything is a method of object. You can find "expression operators" methods in python magic class methods, in the operators.
So, why python has "sexy" things like [x:y], [x], +, -? Because it is common things to most developers, even to unfamiliar with development people, so math functions like +, - will catch human eye and he will know what happens. Similar with indexing - it is common syntax in many languages.
But there is no special ways to express upper, replace, strip methods, so there is no "expression operators" for it.
So, what is different between "expression operators" and methods, I'd say just the way it looks.
Your question is rather broad. For your examples, concatenation, slicing, and indexing are defined on strings and lists using special syntax (e.g., []). But other types may do things differently.
In fact, the behavior of most (I think all) of the operators is constrolled by magic methods, so really when you write something like x + y a method is called under the hood.
From a practical perspective, one of the main differences is that the set of available syntactic operators is fixed and new ones cannot be added by your Python code. You can't write your own code to define a new operator called $ and then have x $ y work. On the other hand, you can define as many methods as you want. This means that you should choose carefully what behavior (if any) you assign to operators; since there are only a limited number of operators, you want to be sure that you don't "waste" them on uncommon operations.
Is there any substantial difference between operators and
methods?
Practically speaking, there is no difference because each operator is mapped to a specific Python special method. Moreover, whenever Python encounters the use of an operator, it calls its associated special method implicitly. For example:
1 + 2
implicitly calls int.__add__, which makes the above expression equivalent1 to:
(1).__add__(2)
Below is a demonstration:
>>> class Foo:
... def __add__(self, other):
... print("Foo.__add__ was called")
... return other + 10
...
>>> f = Foo()
>>> f + 1
Foo.__add__ was called
11
>>> f.__add__(1)
Foo.__add__ was called
11
>>>
Of course, actually using (1).__add__(2) in place of 1 + 2 would be inefficient (and ugly!) because it involves an unnecessary name lookup with the . operator.
That said, I do not see a problem with generally regarding the operator symbols (+, -, *, etc.) as simply shorthands for their associated method names (__add__, __sub__, __mul__, etc.). After all, they each end up doing the same thing by calling the same method.
1Well, roughly equivalent. As documented here, there is a set of special methods prefixed with the letter r that handle reflected operands. For example, the following expression:
A + B
may actually be equivalent to:
B.__radd__(A)
if A does not implement __add__ but B implements __radd__.
I'm new to Scala and I'm having a problem understanding this. Why are there two syntaxes for the same concept, and none of them more efficient or shorter at that (merely from a typing standpoint, maybe they differ in behavior - which is what I'm asking).
In Go the analogues have a practical difference - you can't forward-reference the lambda assigned to a variable, but you can reference a named function from anywhere. Scala blends these two if I understand it correctly: you can forward-reference any variable (please correct me if I'm wrong).
Please note that this question is not a duplicate of What is the difference between “def” and “val” to define a function.
I know that def evaluates the expression after = each time it is referenced/called, and val only once. But this is different because the expression in the val definition evaluates to a function.
It is also not a duplicate of Functions vs methods in Scala.
This question concerns the syntax of Scala, and is not asking about the difference between functions and methods directly. Even though the answers may be similar in content, it's still valuable to have this exact point cleared up on this site.
There are three main differences (that I know of):
1. Internal Representation
Function expressions (aka anonymous functions or lambdas) are represented in the generated bytecode as instances of any of the Function traits. This means that function expressions are also objects. Method definitions, on the other hand, are first class citizens on the JVM and have a special bytecode representation. How this impacts performance is hard to tell without profiling.
2. Reference Syntax
References to functions and methods have different syntaxes. You can't just say foo when you want to send the reference of a method as an argument to some other part of your code. You'll have to say foo _. With functions you can just say foo and things will work as intended. The syntax foo _ is effectively wrapping the call to foo inside an anonymous function.
3. Generics Support
Methods support type parametrization, functions do not. For example, there's no way to express the following using a function value:
def identity[A](a: A): A = a
The closest would be this, but it loses the type information:
val identity = (a: Any) => a
As an extension to Ionut's first point, it may be worth taking a quick look at http://www.scala-lang.org/api/current/#scala.Function1.
From my understanding, an instance of a function as you described (ie.
val f = (x: Int) => x + 1) extends the Function1 class. The implications of this are that an instance of a function consumes more memory than defining a method. Methods are innate to the JVM, hence they can be determined at compile time. The obvious cost of a Function is its memory consumption, but with it come added benefits such as composition with other Function objects.
If I understand correctly, the reason defs and lambdas can work together is because the Function class has a self-type (T1) ⇒ R which is implied by its apply() method https://github.com/scala/scala/blob/v2.11.8/src/library/scala/Function1.scala#L36. (At least I THINK that's what going on, please correct me if I'm wrong). This is all just my own speculation, however. There's certain to be some extra compiler magic taking place underneath to allow method and function interoperability.
I am defining a function that takes as input a function and I want to specify it in the input type i.e. Operat[_?FunctionQ]:=...
But there is no functionQ as of yet in mathematica. How do I get aroud this except not specifying any type at all.
Any ideas?
Oh!
This: Test if an expression is a Function?
may be the answer i am looking for. I am reading further
Is the solution proposed there robust?, i.e.:
FunctionQ[_Function | _InterpolatingFunction | _CompiledFunction] = True;
FunctionQ[f_Symbol] := Or[
DownValues[f] =!= {},
MemberQ[ Attributes[f], NumericFunction ]]
FunctionQ[_] = False;
The exhibited definition has great utility. The question is: what exactly constitutes a function in Mathematica? Pure functions and the like are easily to classify as functions, but what about definitions that involve pattern-matching? Consider:
h[g[x_]] ^:= x + 1
Is h to be considered a function? If so, it will be hard to identify as it will entail examining the up-values of every symbol in the system to make that determination. Is g a function? It has an up-value, but g[x] is an inert expression.
What about head composition:
f[x_][y_][z_] := x + y + z
Is f a function? How about f[1] or f[1][2]?
And then there are the various capabilities like JLink and NETLink:
Needs["JLink`"]
obj = JavaNew["java.util.Date"]
obj#toString[]
Is obj#toString a function?
I hate to bring up these problems without offering solutions -- but I want to emphasize that the question as to what constitutes a function in the Mathematica context is a tricky one. It is tricky from both the theoretical and practical standpoints.
I think that the answer to whether the exhibited function test is complete really depends upon the types of expressions that you will be feeding it in your specific application.
I wanted to ask how can I can write this in MATLAB.
I want to integrate fp(z) with z(0,x). I tried this :
fpz=#(z) f1x(z) ./ quadl(f1x(z),0,1);
sol=int(fpz,0,x) --> i also tried sol=quadl(fpz,0,x)
y=solve('y=sol',x)
xf=# (y) y ; -->this is the function i want
where f1x=# (x) 1 ./(x.^2+1) and fpx = #(x) f1x(x) ./ quadl(f1x,0,1);
but it doesn't work.
Hello,thanks for helping.
The problem is that i want an analytically solution and i can't get one.
I want f1x to give me " 1/x^2+1" , fpx "4/pi*(1+x^2) and fpz "4ArcTan(x)/pi", instead of giving me "f1x=# 1./(x^2+1)"..
With the code you send me ,still the same problem.
I managed to come into this :
f1x=# (x) 1 ./(x.^2+1)
fpx = #(x) f1x(x) ./ quadl(f1x,0,1)
f2z=# (z) 1 ./(z.^2+1);
fpz=#(z) fpx(z) ./ quadl(f2z,0,1)
sol=int(fpz(z),z,0,x)
y=solve(subs('y=sol'),x)
xf=# (y) y
The "sol" and "y=" gives me analytically answer but it is wrong because i assume f1x and fpx,fpz doesn't return into analytically expressions.
0 Your definition of fpz doesn't make any sense; as Marcin already said, you're trying to integrate something that isn't a function. This shouldn't be a problem for your alternative version with f2z. I think the code in the original question should have had just f1x rather than f1x(z) in the first line.
1 Your revised version with f2z has a different problem: now in fpz you aren't actually providing the function with an argument.
The following code seems to be the kind of thing you had in mind, and works fine for me (in MATLAB R2008a, as it happens, but none of this should be different in other versions):
f1x = #(x) 1 ./ (x.^2+1);
fpx = #(x) f1x(x) ./ quadl(f1x,0,1);
fpz = #(z) fpx(z) ./ quadl(fpx,0,1);
Now evaluating fpz(3), for instance, spins for about half a second (on my old slow laptop computer) and returns 0.1273.
So I think the problems you've been having with integration of anonymous functions are just a matter of not being quite careful enough to distinguish between the function itself and a particular value of the function.
You have some further questions about the "solve" and "int" functions in the Symbolic Math Toolbox. You should take the following with a pinch of salt because I don't have that toolbox and am relying on the online documentation for it.
3 You're feeding the names of functions you've defined in MATLAB to the Symbolic Math Toolbox functions. I don't think that is supposed to work; "int" and "solve" expect explicit algebraic expressions, not MATLAB functions. (And, further, your functions all use numerical integration -- quad, quadl, etc. -- and there's no possible way that the symbolic functions can do anything useful with that.)
Finally: When you're asking questions of this sort, it's helpful if rather than "it doesn't work" you say how it doesn't work. For instance, your most recent comment is much more useful ("it gives me ..." followed by the actual output you get from MATLAB).
can i somehow find all functions/macros that take a specific type of parameter ?
for example, what function accepts a Namespace object as parameter ?
(this is because i can create a namespace and store it in a var, but i don't know where i could use that var; what function might i pass that var to ?)
here is some code:
user=> (def working-namespace (create-ns 'my-namespace))
#'user/working-namespace
;i created a namspace and want to use it later
user=> (class working-namespace)
clojure.lang.Namespace
; out of curiosity i found out that "working-namespace" is a Namespace object
user=> (ns working-namespace)
nil
working-namespace=>
; but how do i switch to it ? this didn't do what i wanted...
user=> (refer working-namespace)
java.lang.ClassCastException: clojure.lang.Namespace cannot be cast to clojure.lang.Symbol (NO_SOURCE_FILE:0)
; this did not work either as my expectations
user=> (the-ns working-namespace)
#<Namespace my-namespace>
user=> (class (the-ns working-namespace))
clojure.lang.Namespace
; great, this gave me the same thing, a Namespace
hence the question: how do i use it dynamically (that's why i had put my namespace into a var) ? how do i get something useful for me from a var that points to a namespace ?
i can try look around for functions that make use of a Namespace object or that convert it to something else. i did and only found "intern". searching by hand not seems not that promising
what if i have this problem a million time ? is there an automated way to get me what i'm looking for without having to ask around each time ?
In Clojure 1.2 and previous function arguments dont have types. every function argument is an object. So the question really becomes "how do i find functions that will cast the object I pass them into this type. so searching for type hints will find some of them, though it wont get you everything. I wish it where more possible to answer this in general.
starting with 1.3 (current dev branch 9/2010) function paramerters and return types can have a defined type and will be passed/returned as that type instead of being cast to object and then cast on the other side. This drops one of the zeros from the exacution time of numerical functions with the important limitation that it only works for :static functions and only with direct calls (ie: not through map/reduce/filter/etc.) There is not a lot published on this change yet though it has the important breaking change that integers are no longer boxed by default and integer (actually Long) overflow throws an exception. you can read more here
(defn ^:static fib ^long [^long n]
(if (<= n 1)
1
(+ (fib (dec n)) (fib (- n 2)))))
so after 1.3 is released and widely adopted you will see code with more commonly defined types because they will offer a big speed benefit and then you will be able to find more functions by argument type though still not all of them.
At the same lecture where I learned about function argument types, Rich mentioned plans in the distant Clojure future (after 'Clojure in Clojure') about better support for exposing the compiler internals to tools such as IDEs. So there is hope that someday you will get a real answer to this question.
Dynamic languages make this slightly more difficult in practice and a lot harder in theory.
You already got a good answer from Arthur, so I'll only answer the "how do i get something useful for me from a var that points to a namespace ?". From (doc ns), note that it says unevaluated:
user=> (doc ns)
-------------------------
clojure.core/ns
([name docstring? attr-map? references*])
Macro
Sets *ns* to the namespace named by name (unevaluated), creating it
Now there's something you could do with in-ns if you want (the whole namespace object -> string -> symbol conversion is probably stupid, but enough to illustrate my point):
user=> (in-ns (symbol (str working-namespace)))
#<Namespace my-namespace>
my-namespace=>
I don't think you can do that without a lot of hackery in a dynamic language. If you want to now what function that take namespaces look at the documentation of the namespace stuff.
For example cleaning namespaces or reload them.
You wrote:
user=> (ns working-namespace)
nil
working-namespace=>
; but how do i switch to it ? this didn't do what i wanted...
But you did switch to the working-namespace namespace (that's why the prompt changed), so I'm not clear as to what "you wanted".
As I noted earlier, you need to present the ultimate problem are you trying to solve. It's entirely likely that messing with namespace objects won't be the solution.