Suppose I have a dumb Frege function that constructs a pair of Nums.
newPair :: (Num α, Num β) => α -> β -> (α, β)
newPair = (,)
-- alternatively -- newPair x y = (x, y)
Attempting to call this function from Java, however, a PreludeBase.CNum<α> and a PreludeBase.CNum<β> are demanded in addition to the expected Lazy<α> and Lazy<β>. Likewise with Show types, where
showSomething :: (Show α) => α -> String
showSomething = show
-- alternatively -- showSomething x = show x
would require a PreludeBase.CShow<α> in addition to the expected parameter.
What is the proper way to pass constrained Frege objects to and from Java?
Good question, since this is not explained in the wiki yet.
As in all cases like this, I recommend to use the
:java
command in the REPL. For example:
frege> newPair 1 2.3
frege> :java
You will then get a window that contains among all active definitions one that corresponds to this call. A simple text search can help find the place where newPair is called. This should help to resolve such issues most of the time.
In your case, the relevant part would look like:
Console.<Integer, Double>numPair(
PreludeBase.INum_Int.it,
PreludeBase.IReal_Double.it,
Thunk.<Integer>lazy(1),
Thunk.<Double>lazy(2.3))
Here is a short overwiew about how type classes and instances are named and how you can get at them.
module x.y.Z where
class Xable where ...
This results in a Java-interface with the fully qualified name
x.y.Z.CXable
And this:
module a.b.C where
import x.y.Z
data MyType ... = ....
instance Xable MyType where ...
results in some class
a.b.C.IXable_MyType /* implements CXable<TMyType> */
If your instance definition does not have constraints themselves, there will be a singleton instance that you can use.
a.b.C.IXable_MyType.it
Otherwise, you need to construct a new instance by passing all constraints as argument to the constructor. For example, the Show instance for
Maybe Int
would look something like this:
new IShow_Maybe(IShow_Int.it)
since the instance head lists a constraint for the Maybe element type:
instance Show a => Show (Maybe a)
Note that you need to know the actual type fully, you can't make a generic type class instance. This is never a problem in Frege itself, as all needed instances are passed to a polymorphic function from the caller. However, as it stands, we don't have constraints in native functions.
Should you need something like this, you can achieve the functionality in most cases by just passing the function you wanted to call as argument.
For example, this doesn't work:
pure native myMethod :: Show a => a -> ...
but this should:
pure native myMethod :: (a -> String) -> a -> ....
myMethod show (Just 47)
The example java code above also reveals that it is not always as easy as described. For example, it so happens that the Double type doesn't have a separate Num instance, but just one for Real which is a subclass of Num. Unfortunately, only the compiler has the knowledge of what instances are actually present for some type, and which ones are implicit, that is, provided by an instance for a sub-class. Again, the REPL is the best way to find this out.
Related
I have an ArrayList of Strings, and am adding a method to sort the ArrayList
list.sort(Comparator.comparing(x -> x.length()));
When I write x and press ctrl + space eclipse does not suggest the methods of the String class, but only shows methods of the Object class.
Please help me configure eclipse to show the exact method suggestions in this case.
In regular cases eclipse is exact.
This is a two-fold issue, one with eclipse, and one with java semantics.
Java Semantics
A quick example:
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.sort(Comparator.comparing(x -> x.|));
}
Assume you press ctrl + space at the | (cursor) position. Then eclipse has to infer a lot of information to know, that x is in fact an element of type String. First, the list's generic type String must be known (it is, eclipse can deduce this). Then the Comparator.comparing method needs to know, that it must return an instance of a Comparator which compares Strings, which eclipse could deduce, but here is the first issue: The Comparator could be one that compares not just Strings, but also any other kind of Object. What if you wanted to pass a method to myList.sort that is more general than the generic Comparator<String>? To be more precise: The List.sort method can take (in your case) any Comparator of type Comparator<? super String>. And ? super String is already either Object or String.
So in your example. the type of x could just be an object, eclipse cannot ultimately decide. However, you can write your lambda expression differently, to make it clear:
myList.sort(Comparator.comparing((String x) -> x.|));
In this case, the completion suggestion could be more helpful (depending on the version of eclipse).
eclipse AST issues with incomplete lambdas
An incomplete lambda expression is more often than not such an upset in the syntax of the entire file, that eclipse cannot determine the syntax tree at that position correctly. That means, that eclipse cannot deduce, that the code you are writing is supposed to be a lambda expression, where x is the parameter of the lambda function, and you want to complete that. This issue could be addressed, if the tokenizer and AST-parser of eclipse are adapted accordingly (which might have already been tried). Whether this is possible at all, I cannot answer. I only know it helps, to write a "full" lambda, with a method block, and convert that to a "slim" lambda later on:
myList.sort(Comparator.comparing((String x) -> { return x.| }));
For the above case, the completion should work (IF you specify String as absolute type of the Comparator, as I have done in the example).
Issues like this stem from the question of how to interpret the characters and therefore deduce, what the programmer might intent to write (the process of auto completion and completion suggestion).
eclipse is very strong in isolating a reference to a named entity, when in regular code, like a method block, a for loop, or any other construct. That is why it works well there. The syntax tree is usually easy to process then.
However when using lambdas, eclipse (and any other IDE for that matter) have a harder time. This is due to the fact, that lambdas work by inferring a lot of implicit information, which would otherwise need to be written explicitly (for example in an explicit implementation of the interface).
If everything else fails, you can create the explicit interface at that position and then convert to a lambda after completing it.
I am trying to understand Interpreter Design Pattern in Java. I am getting the following code from Wikipedia. There is written
interface Expression {
public int interpret(Map<String,Expression> variables);
}
Could you explain me what is going on here with respect to Expression being the value of Map, which is inside in an Interface of Type Expression. Is it something like recursive calling ? Kindly explain.
To answer your question, Yes same function interpret() is called again and again but they are not of the same class. Hence it is not actually recursive function.
Used wiki code to explain the Interpreter pattern, but you need to go to and fro to wiki page to understand the whole picture,
http://en.wikipedia.org/wiki/Interpreter_pattern
Interpreter pattern is the one in which each and every variable and the operator in the given expression is represented as a separate class, and then the evaluation happens on the objects of these classes.
Expression - class, expression - ((y+z)-x)
In the case of the wiki example which you pointed out, when you call the constructor of Evaluator in the main(), only expression will be constructed (again its another Expression object) and saved in the syntaxTree reference variable of Evaluator.
To give a gist of whats happening there with expression: x y z + -
First variables x,y,z will be stored as such in the expressionStack variable
When you encounter +, (y+z) will be pushed into the expressionStack
After - token, ((y+z)-x) Expression object will be in the expressionStack (check the push and pop which is happening for the operator in Evaluator)
so once the constructor of Evaluator is done, you will have Expression object whose implementation is again an Expression denoted as ((y+z)-x).
Now comes the interesting part in main(), you are substituting values for the variable (x,y,z) using Number class and it happens in this order,
main () sentence.interpret(variables);
Evaluator.syntaxTree.interpret(variables);
Variable.interpret(variables) // Here the actual values(5,10,42) gets substituted for x, y, z.
and then the Expression is evaluated.
If you see interpret() of Variables class, it is slightly different where it gets the corresponding Number object of the variable, using the context passed. This is the actual substitution of variables to numbers using the context object passed in main(). This in turn calls the interpret() of Number which just returns the number and the operation happens as ((10+5)-42) = -27.
Advantage:
By using this technique you can keep on adding operations (plus, minus) without affecting the existing operations and one operation is independent of other. It is used in SQL queries and other interpreters.
Thanks,
Prasanna V.
An interface defines methods that a class has to implement if it has the interface.
class MathExpression implements Expression {
public int interpret(Map<String,Expression> variables) {
//insert code here
}
}
I wouldn't describe it as a recursive call. An accurate description is the interface is self-referencing itself in a method call.
Expression expression = new MathExpression();
expression.interpret(stringToExpressionMap);
The advantage of this is you can define a behavior in that class without having to know the specific implementation of that class.
Is there any such equivalent of Java
String myMethod (MyClass argument) {...}
in Python?
Thank you, Tomas
No. (And more stuff to round this up to 15 characters...)
No, there is not.
In fact, checking types is considered "un-Pythonic", because an object of any type that looks enough like the expected type should be treated equally.
Python 3.x has function annotations where you can declare argument and return types:
def myMethod(argument: MyClass) -> str:
...
But currently Python does nothing with them, they serve as documentation only.
I just want to say that I'm in full agreement that type checking is evil. But python is also incredibly flexible and I'm in the mood to be evil. This code will take effect at runtime and not compile time. You could do something similar for return type. Something like this could be useful for debugging and, because it's a decorator, it's easy enough to remove.
For it to be useful for debugging you would have to have a situation where two types had all the same attributes that were getting accessed but with different semantics. So that's a pretty limited case. Other than that, you're about to get a typerror anyways when this code runs. The good news is that this is almost never a problem. I really don't know why people from statically typed languages make such a big deal over it.
def types(*args, **kwargs):
arg_types = args
kwarg_types = kwargs
def decorator(f):
def func(*args, **kwargs):
for arg, arg_type in zip(args, arg_types):
if not isinstance(arg, arg_type):
raise TypeError("Wrong type suckah")
for kw, arg in kwargs.items():
if not isinstance(arg, kwarg_types[kw]):
raise TypeError("this is a bad error message")
return f(*args, **kwargs)
return func
return decorator
#types(int, str, bool, flag=bool)
def demo(i, strng, flag=False):
print i, strng, flag
demo(1, "foo", True)
try:
demo("foo", "bar", flag="foobar")
except TypeError:
print "busted on posargs"
try:
demo(1, "foo", flag=2)
except TypeError:
print "busted on keyargs"
try:
demo(1, "foo", 3)
except TypeError:
print "no use sneaking it through"
No.
In Python, it's the program's
responsibility to use built-in
functions like isinstance() and
issubclass() to test variable types
and correct usage. Python tries to
stay out of your way while giving you
all you need to implement strong type
checking.
from Why is Python a dynamic language and also a strongly typed language. Also
In a dynamically typed language, a
variable is simply a value bound to a
name; the value has a type -- like
"integer" or "string" or "list" -- but
the variable itself doesn't. You could
have a variable which, right now,
holds a number, and later assign a
string to it if you need it to change.
Further, isinstance() and issubclass() can be used to do type-checking. If you want to make sure that argument is of MyClass type, you can have a check inside the function. You can even type-cast the value of the argument (if you have a constructor accepting such value) and assign it to my_object.
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to have properties and methods that share the same name, but I don't think that comes up much.
The only big benefit I can come up with is readability. Sometimes you might want to know whether something is a method or a property while you're looking at code, but I'm having trouble coming up with specific examples when that would be really helpful. But I am a n00b, so I probably just haven't encountered such a situation yet. I'd appreciate examples of such a situation.
Also, are there other languages where the difference isn't explicit?
Anyways, if you could answer, it will help me be less annoyed every time I make this mistake ^-^.
UPDATE:
Thanks everyone for the awesome answers so far! I only have about a week's worth of js, and 1 day of python, so I had no idea you could reference functions without calling them. That's awesome. I have a little more experience with java, so that's where I was mostly coming from... can anyone come up with an equally compelling argument for that to be the case in java, where you can't reference functions? Aside from it being a very explicit language, with all the benefits that entails :).
All modern languages require this because referencing a function and calling a function are separate actions.
For example,
def func():
print "hello"
return 10
a = func
a()
Clearly, a = func and a = func() have very different meanings.
Ruby--the most likely language you're thinking of in contrast--doesn't require the parentheses; it can do this because it doesn't support taking references to functions.
In languages like Python and JavaScript, functions are first–class objects. This means that you can pass functions around, just like you can pass around any other value. The parentheses after the function name (the () in myfunc()) actually constitute an operator, just like + or *. Instead of meaning "add this number to another number" (in the case of +), () means "execute the preceding function". This is necessary because it is possible to use a function without executing it. For example, you may wish to compare it to another function using ==, or you may wish to pass it into another function, such as in this JavaScript example:
function alertSomething(message) {
alert(message);
}
function myOtherFunction(someFunction, someArg) {
someFunction(someArg);
}
// here we are using the alertSomething function without calling it directly
myOtherFunction(alertSomething, "Hello, araneae!");
In short: it is important to be able to refer to a function without calling it — this is why the distinction is necessary.
At least in JS, its because you can pass functions around.
var func = new Function();
you can then so something like
var f = func
f()
so 'f' and 'func' are references to the function, and f() or func() is the invocation of the function.
which is not the same as
var val = f();
which assigns the result of the invocation to a var.
For Java, you cannot pass functions around, at least like you can in JS, so there is no reason the language needs to require a () to invoke a method. But it is what it is.
I can't speak at all for python.
But the main point is different languages might have reasons why syntax may be necessary, and sometimes syntax is just syntax.
I think you answered it yourself:
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
Consider the following:
if (colorOfTheSky == 'blue')
vs:
if (colorOfTheSky() == 'blue')
We can tell just by looking that the first checks for a variable called colorOfTheSky, and we want to know if its value is blue. In the second, we know that colorOfTheSky() calls a function (method) and we want to know if its return value is blue.
If we didn't have this distinction it would be extremely ambiguous in situations like this.
To answer your last question, I don't know of any languages that don't have this distinction.
Also, you probably have a design problem if you can't tell the difference between your methods and your properties; as another answer points out, methods and properties have different roles to play. Furthermore it is good practice for your method names to be actions, e.g. getPageTitle, getUserId, etc., and for your properties to be nouns, e.g., pageTitle, userId. These should be easily decipherable in your code for both you and anyone who comes along later and reads your code.
If you're having troubles, distinguishing between your properties and methods, you're probably not naming them very well.
In general, your methods should have a verb in them: i.e. write, print, echo, open, close, get, set, and property names should be nouns or adjectives: name, color, filled, loaded.
It's very important to use meaningful method and property names, without it, you'll find that you'll have difficulty reading your own code.
In Java, I can think of two reasons why the () is required:
1) Java had a specific design goal to have a "C/C++ like" syntax, to make it easy for C and C++ programmers to learn the language. Both C and C++ require the parentheses.
2) The Java syntax specifically requires the parentheses to disambiguate a reference to an attribute or local from a call to a method. This is because method names and attribute / local names are declared in different namespaces. So the following is legal Java:
public class SomeClass {
private int name;
private int name() { ... }
...
int norm = name; // this one
}
If the () was not required for a method call, the compiler would not be able to tell if the labeled statement ("this one") was assigning the value of the name attribute or the result of calling the name() method.
The difference isn't always explicit in VBA. This is a call to a Sub (i.e. a method with no return value) which takes no parameters (all examples are from Excel):
Worksheets("Sheet1").UsedRange.Columns.AutoFit
whereas this is accessing an attribute then passing it as a parameter:
MsgBox Application.Creator
As in the previous example, parentheses are also optional around parameters if there is no need to deal with the return value:
Application.Goto Worksheets("Sheet2").Range("A1")
but are needed if the return value is used:
iRows = Len("hello world")
Because referencing and calling a method are two different things. Consider X.method being the method of class X and x being an instance of X, so x.method == 'blue' would'nt ever be able to be true because methods are not strings.
You can try this: print a method of an object:
>>> class X(object):
... def a(self):
... print 'a'
...
>>> x=X()
>>> print x.a
<bound method X.a of <__main__.X object at 0x0235A910>>
Typically properties are accessors, and methods perform some sort of action. Going on this assumption, it's cheap to use a property, expensive to use a method.
Foo.Bar, for example, would indicate to me that it would return a value, like a string, without lots of overhead.
Foo.Bar() (or more likely, Foo.GetBar()), on the other hand, implies needing to retrieve the value for "Bar", perhaps from a database.
Properties and methods have different purposes and different implications, so they should be differentiated in code as well.
By the way, in all languages I know of the difference in syntax is explicit, but behind the scenes properties are often treated as simply special method calls.
I couldn't find documentation on an equivalent of Java's final in Python, is there such a thing?
I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.
There is no final equivalent in Python. To create read-only fields of class instances, you can use the property function, or you could do something like this:
class WriteOnceReadWhenever:
def __setattr__(self, attr, value):
if hasattr(self, attr):
raise Exception("Attempting to alter read-only value")
self.__dict__[attr] = value
Also note that while there's #typing.final as of Python 3.8 (as Cerno mentions), that will not actually make values final at runtime.
Having a variable in Java be final basically means that once you assign to a variable, you may not reassign that variable to point to another object. It actually doesn't mean that the object can't be modified. For example, the following Java code works perfectly well:
public final List<String> messages = new LinkedList<String>();
public void addMessage()
{
messages.add("Hello World!"); // this mutates the messages list
}
but the following wouldn't even compile:
public final List<String> messages = new LinkedList<String>();
public void changeMessages()
{
messages = new ArrayList<String>(); // can't change a final variable
}
So your question is about whether final exists in Python. It does not.
However, Python does have immutable data structures. For example, while you can mutate a list, you can't mutate a tuple. You can mutate a set but not a frozenset, etc.
My advice would be to just not worry about enforcing non-mutation at the language level and simply concentrate on making sure that you don't write any code which mutates these objects after they're assigned.
Python 3.8 (via PEP 591) adds Final variables, functions, methods and classes. Here are some ways to use it:
#final Decorator (classes, methods)
from typing import final
#final
class Base:
# Cannot inherit from Base
class Base:
#final
def foo(self):
# Cannot override foo in subclass
Final annotation
from typing import Final
PI: Final[float] = 3.14159 # Cannot set PI to another value
KM_IN_MILES: Final = 0.621371 # Type annotation is optional
class Foo:
def __init__(self):
self.bar: Final = "baz" # Final instance attributes only allowed in __init__
Please note that like other typing hints, these do not prevent you from overriding the types, but they do help linters or IDEs warn you about incorrect type usage.
An assign-once variable is a design issue. You design your application in a way that the variable is set once and once only.
However, if you want run-time checking of your design, you can do it with a wrapper around the object.
class OnePingOnlyPleaseVassily(object):
def __init__(self):
self.value = None
def set(self, value):
if self.value is not None:
raise Exception("Already set.")
self.value = value
someStateMemo = OnePingOnlyPleaseVassily()
someStateMemo.set(aValue) # works
someStateMemo.set(aValue) # fails
That's clunky, but it will detect design problems at run time.
There is no such thing. In general, the Python attitude is "if you don't want this modified, just don't modify it". Clients of an API are unlikely to just poke around your undocumented internals anyway.
You could, I suppose, work around this by using tuples or namedtuples for the relevant bits of your model, which are inherently immutable. That still doesn't help with any part of your model that has to be mutable of course.
you can simulate something like that through the descriptor protocol, since it allows to define reading and setting a variable the way you wish.
class Foo(object):
#property
def myvar(self):
# return value here
#myvar.setter
def myvar(self, newvalue):
# do nothing if some condition is met
a = Foo()
print a.myvar
a.myvar = 5 # does nothing if you don't want to
As of 2019 and PEP 591, Python has a Final type. It won't be available in the standard library until the release of Python 3.8, but until then you can use it via the typing-extensions library. It won't work as final works in Java though as Python is still a dynamically typed language. But if you use it together with a static type checker like mypy it will give you very similar benefits.
There is also a final decorator that can be applied to mark class methods as final and preventing from being overridden. Again this is only checked at "compile-time", so you'd need to include a static type checker in your workflow.
Python has no equivalent of "final". It doesn't have "public" and "protected" either, except by naming convention. It's not that "bondage and discipline".
http://code.activestate.com/recipes/576527/ defines a freeze function, although it doesn't work perfectly.
I would consider just leaving it mutable though.
Python indeed does not have a final type, it does have immutable types such as tuples but that is something else.
Some of the other Answers here make classes full of pseudo final variables and I prefer my class to only have a few Final types, so I suggest using an descriptor to create the final type:
from typing import TypeVar, Generic, Type
T = TypeVar('T')
class FinalProperty(Generic[T]):
def __init__(self, value: T):
self.__value = value
def __get__(self, instance: Type, owner) -> T:
return self.__value
def __set__(self, instance: Type, value: T) -> None:
raise ValueError("Final types can't be set")
If you use this class like so:
class SomeJob:
FAILED = FinalProperty[str]("Failed")
Then you will not be able to set that variable in any instance of that class.
Unfortunately as with the WriteOnceReadWhenever answer you can still set the class variable.
job = SomeJob()
job.FAILED = "Error, this will trigger the ValueError"
SomeJob.FAILED = "However this still works and breaks the protection afterwards"
Although this is an old question, I figured I would add yet another potential option: You can also use assert to verify a variable is set to what you originally intended it to be set to – a double checking if you will. Although this is not the same as final in Java, it can be used to create a similar effect:
PI = 3.14
radius = 3
try:
assert PI == 3.14
print PI * radius**2
except AssertionError:
print "Yikes."
As seen above, if PI were for some reason not set to 3.14, an AssertionError would be thrown, so a try/except block would probably be a wise addition. Regardless, it may come in handy depending on your situation.
As of Python 3.8, Python does have a keyword "final". However, it is a hint and is not enforced at runtime.