How does hybrid typing work? - raku

Wikipedia says "Perl 6 offers a hybrid typing system whereby the programmer may choose to use static typing, use dynamic typing, or mix the two." How does hybrid typing work? Does using static typing in Perl simply mean that I declare a type, and have to explicitly cast strings to numbers and vice versa in exchange for safety and run time speed? I've noticed there seems to be very little information on this feature.

As I understand it, hybrid typing simply means that type annotations are supported, but optional:
my Int $i = 0; # static typing
my $i = 0; # dynamic typing
When you use the explicit type annotations, the compiler may check things for you and maybe optimize the code better. There are similar features in other languages, too, like Objective-C:
NSString *foo = #"foo"; // explicit type signature, static typing
id foo = #"foo"; // dynamic typing
Technically speaking, this is not exactly the difference between static and dynamic typing. There are languages that have a static type system that doesn’t require the explicit type annotations. In Swift or Haskell, you can say things like let f = 0 (without a type annotation) and still get static type checking thanks to type inference. See also What to know before debating type systems.
There are also other, more interesting features regarding the difference between static and dynamic typing in Perl 6, see Jnthn’s talk.

Related

How do we determine a language is dynamic or static? an example is Swift

I have been reading some posts and it always get me confused.
1, some says a language is static/dynamic by how the type is determined, in runtime or in compile time. But should we say the language is static/dynamic typing language rather than static/dynamic language?
2, in some comparison of swift vs objective-c. We know that objective-c uses its runtime to do dynamic method dispatch. And some uses this as a reason to say that the language/objective-c is dynamic, is this true?!
3, I'm sometimes confused about the OOP's polymorphism, some says in order to make it work, the language HAS to support method dynamic dispatching. Is this right?
4, for swift, I know it's a static typing language, but is it a static or dynamic method dispatching language? and is it a static or dynamic language overall??
I've never heard of the term "static language" or "dynamic language." The usual terms I've heard of are "statically typed language" or "dynamically typed language."
"Dynamic" isn't a defined term in this context, so there's not much to say here.
Polymorphism has multiple different meanings, so I'll assume you mean subtype polymorphism. In that case, yes, dynamic dispatch is necessary. The whole idea is that you want objects of different types to behave in their own way in response to the same message (method call). The only way to do this is to decouple messages and function invocations, so that an appropriate function can be called at runtime depending on the type of the receiver of the message.
Swift is a statically typed language, through and through. This might be obscured a bit by type inference. If you have an expression like
func someFunction() -> Int { return 123 }
let x = someFunction()
The type inference doesn't mean "x has some type that will be figured out at runtime." To the contrary, it means "The type of x can be deduced at runtime because we already know the type of someFunction."
All types in Swift are known at compile time. In the worst case, a must at least have type Any, which is still a type. It's not a particularly useful type (because there isn't much an Any is guaranteed to be able to do), but it's still a type.
There is some confusion in that there's talk of types at compile time and runtime types. Here's an example:
class Car {
func vroom() { print("vroom") }
}
class SportsCar: Car {
override func vroom() { print("VROOOOOM") }
}
let car: Car = SportsCar()
func driveSportsCar(_: SportsCar) { print("driving") }
// Compile types are what determine usage compatibility
driveSportsCar(car) // 💥 cannot convert value of type 'Car' to expected argument type 'SportsCar'
// Runtime types are what determine method implementations
car.vroom() // => "VROOOOOM"
In this example, car has a compile time type of Car, and a runtime type of SportsCar. The compile time type determines how it can be used, where it can be passed, etc. For example, you couldn't pass car to a driveSportsCar() function, because even though its runtime type is SportsCar, its compile time type is Car, which isn't compatible.
The runtime type of an object is what determines the method implementations to be called.
Swift is a statically ‘typed’ language which means that It performs type checks before run-time.
Swift uses direct dispatch, table dispatch with its witness table, or message dispatch (obj-c ) depending on various situations, you can take a look at this article: https://www.raizlabs.com/dev/2016/12/swift-method-dispatch/ some of the examples are outdated but the concepts will be made more clear
Static dispatch doesn’t support polymorphism because it needs to know which implementation for a method will be executed at compile time.
Hope this helps a bit.

Static, extern and inline in Objective-C

What do static, extern and inline (and their combinations) mean in Objetive-C using the LLVM compiler?
Also, I noticed that there are CG_EXTERN and CG_INLINE macros. Should we be using those instead?
(I couldn't find a source with a clear explanation so I thought it might be useful to create one here, or point to it if someone knows one)
What do static, extern and inline (and their combinations) mean in Objetive-C using the LLVM compiler?
The same as in C, unless you compile as ObjC++ -- then they mean the same as found in C++.
So here is an introduction for C, but read the links if you are ready to use these because the details are important:
Extern
Summary: Indicates that an identifier is defined elsewhere.
Details: http://tigcc.ticalc.org/doc/keywords.html#extern
Static
Summary (value): Preserves variable value to survive after its scope ends.
Summary (function): Effectively emits unnamed copies - useful for private functions in C, and can be used to escape multiple definition errors when used with inline functions.
Details: http://tigcc.ticalc.org/doc/keywords.html#static
Inline
Summary: Suggests the body of a function should be moved into the callers.
Details: http://tigcc.ticalc.org/doc/gnuexts.html#SEC93
Note that inline and static are quite a bit more complex in C++ (like pretty much everything in C++).
I also found that there are CG_EXTERN and CG_INLINE macros. Should we be using those instead?
No.
Instead, you should specify your own, with your own meanings, if you need this type of functionality. CG_EXTERN and CG_INLINE have specific meanings (which may change), and are meant to be used in their defined context -- also, you don't want to have to include a whole handful of frameworks (all CoreGraphics/ApplicationServices/CoreFoundation/etc.) when you want to specify something is extern in a way that works in C and C++.
Justin covered most of it, but I found some other nice resources for those who want to dig deeper:
By declaring a function inline you tell the compiler to replace the complete code of that function directly into the place from where it was called. This is a rather advanced feature that requires understanding of lower-level programming.
Inline functions
This SO question has an enormous answer about extern variables - variables defined "somewhere else" - but need to be used also "here".
Static preserves variable life outside of scope. The Variable is visible within the scope it was declared.
What does a static variable mean?

Why don't oop languages have a 'read only' access modifier?

Every time I write trivial getters (get functions that just return the value of the member) I wonder why don't oop languages simply have a 'read only' access modifier that would allow reading the value of the members of the object but does not allow you to set them just like const things in c++.
The private,protected,public access modifiers gives you either full (read/write) access or no access.
Writing a getter and calling it every time is slow, because function calling is slower than just accessing a member. A good optimizer can optimize these getter calls out but this is 'magic'. And I don't think it is good idea learning how an optimizer of a certain compiler works and write code to exploit it.
So why do we need to write accessors, read only interfaces everywhere in practice when just a new access modifier would do the trick?
ps1: please don't tell things like 'It would break the encapsulation'. A public foo.getX() and a public but read only foo.x would do the same thing.
EDIT: I didn't composed my post clear. Sorry. I mean you can read the member's value outside but you can't set it. You can only set its value inside the class scope.
You're incorrectly generalizing from one or some OOP language(s) you know to OOP languages in general. Some examples of languages that implement read-only attributes:
C# (thanks, Darin and tonio)
Delphi (= Object Pascal)
Ruby
Scala
Objective-C (thanks, Rano)
... more?
Personally, I'm annoyed that Java doesn't have this (yet?). Having seen the feature in other languages makes boilerplate writing in Java seem tiresome.
Well some OOP languages do have such modifier.
In C#, you can define an automatic property with different access qualifiers on the set and get:
public int Foo { get; private set; }
This way, the class implementation can tinker with the property to its heart's content, while client code can only read it.
C# has readonly, Java and some others have final. You can use these to make your member variables read-only.
In C#, you can just specify a getter for your property so it can only be read, not changed.
private int _foo;
public int Foo
{
get { return _foo; }
}
Actually, no they aren't the same. Public foo.getX() would still allow the internal class code to write to the variable. A read-only foo.x would be read-only for the internal class code as well.
And there are some languages that do have such modifier.
C# properties allow to define read only properties easily. See this article.
Not to mention Objective-C 2.0 property read-only accessors
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html
In Delphi:
strict private
FAnswer: integer;
public
property Answer: integer read FAnswer;
Declares a read-only property Answer that accesses private field FAnswer.
The question largely boils down to: why does not every language have a const property like C++?
This is why it's not in C#:
Anders Hejlsberg: Yes. With respect to
const, it's interesting, because we
hear that complaint all the time too:
"Why don't you have const?" Implicit
in the question is, "Why don't you
have const that is enforced by the
runtime?" That's really what people
are asking, although they don't come
out and say it that way.
The reason that const works in C++ is
because you can cast it away. If you
couldn't cast it away, then your world
would suck. If you declare a method
that takes a const Bla, you could pass
it a non-const Bla. But if it's the
other way around you can't. If you
declare a method that takes a
non-const Bla, you can't pass it a
const Bla. So now you're stuck. So you
gradually need a const version of
everything that isn't const, and you
end up with a shadow world. In C++ you
get away with it, because as with
anything in C++ it is purely optional
whether you want this check or not.
You can just whack the constness away
if you don't like it.
See: http://www.artima.com/intv/choicesP.html
So, the reason wy const works in C++ is because you can work around it. Which is sensible for C++, which has its roots in C.
For managed languages like Java and C#, users would expect that const would be just as secure as, say, the garbage collector. That also implies you can't work around it, and it won't be useful if you can't work around it.

Are there any useful naming conventions for *your* constant/static variable in Cocoa?

I know that constants start with the k prefix, but does anyone have their own constant prefix, so they can easily get completion on their constants, instead of Apple's?
I use a three letter prefix for my classes because of my company name, let's pretend it's OMG. I tried prefixing my constants with omgkConstantName but that isn't very satisfying. I was also toying with either kk or ok (the o is from the OMG.) Or maybe I should do kOMGConstantName, that seems more Cocoa-ish?
It seems really useful to quickly get to your own constants, the same way you might want to get to your own classes. Does anyone do this? Is it terrible Cocoa style?
Also, is there a good naming convention for static variables you would only use in one class, like keys for a JSON dictionary? Should they have the k? Should they start uppercase, or do they follow normal case conventions?
// Static Variables
static NSString *searchTextKey = #"searchText";
static NSString *searchResultsKey = #"searchResults";
(more)
I try to consistently use kJAFoo (or kXXFoo where XX is a project prefix) for my public constants – especially actual consts which are exported symbols – but generally use kFoo for enums or static consts inside an implementation file. Similarly, I use sFoo for static variables and gJAFoo in the rare cases where I use exported globals.
None of these cases are as important as namespacing classes (and methods in categories on imported classes), though, since most types of conflicts will emerge at compile or link time rather than runtime.
Apple's Coding Guidelines for Cocoa recommends to use the same naming conventions for enumerations as for functions. Following this advice, OMGConstantName would be correct.
I normally make constants Pascal case.
If you choose to follow the 'namespacing convention' of putting a prefix on everything then you'd use that as well.
So I'd normally do
static NSString *SearchTextKey = #"searchText";
you may choose to namespace it though which would have it be (assuming your prefix is ZK)
static NSString *ZKSearchTextKey = #"searchText";
In general I only namespace things that are used in multiple projects, following the google recommendation (or at least it was when I was settling upon my naming convention).
The most important thing though is that whatever convention you settle on. Stick to it and be consistent (at least within a given project). At a certain point second guessing yourself is just going to waste time.
I usually follow the same prefix/capitalisation convention as classes, so where Cocoa has NSTouchPhaseBegan I might have GLTuneNameKey.

Regular expressions in an Objective-C Cocoa application

Initial Googling indicates that there's no built-in way to do regular expressions in an Objective-C Cocoa application.
So four questions:
Is that really true?
Are you kidding me?
Ok, then is there a nice open-source library you recommend?
What are ways to get close enough without importing a library, perhaps with the NSScanner class?
I noticed that as of iOS 4.0 Apple provides a NSRegularExpression class. Additionally, as of 10.7, the class is available under OS X.
Yes, there's no regex support in Cocoa. If you're only interested in boolean matching, you can use NSPredicate which supports ICU regex syntax. But usually you're interested in the position of the match or position of subexpressions, and you cannot get it with NSPredicate.
As mentioned you can use regex POSIX functions. But they are considered slow, and the regex syntax is limited compared to other solutions (ICU/pcre).
There are many OSS libraries, CocoaDev has an extensive list.
RegExKitLite for example doesn't requires any libraries, just add the .m and .h to your project.
(My complaint against RegExKitLite is that it extends NSString via category, but it can be considered as a feature too. Also it uses the nonpublic ICU libraries shipped with the OS, which isn't recommended by Apple.)
RegexKit is the best I've found yet. Very Cocoa:y. I'm using the "Lite" version in several of our iPhone apps:
sourceforge
lingonikorg
You can use the POSIX Regular Expressions library (Yay for a POSIX compliant OS). Try
man 3 regex
The cheap and dirty hack solution that I use to solve REGEX and JSON parsing issues is to create a UIWebView object and inject Javascript function(s) to do the parsing. The javascript function then returns a string of the value (or list of values) I care about. In fact, you can store a small library set of functions customized for particular tasks and then just call them as needed.
I don't know if it this technique scales to huge volumes of repeated parsing requests, but for quick transactional stuff it gets the job done without depending on any extra external resources or code you might not understand.
I like the AGRegex framework which uses PCRE, handy if you are used to the PCRE syntax. The best version of this framework is the one in the Colloquy IRC client as it has been upgraded to use PCRE 6.7:
http://colloquy.info/project/browser/trunk/Frameworks/AGRegex
It's very lightweight, much more so than RegExKit (although not as capable of course).
NSRegularExpression is available since Mac OS X v10.7 and IOS 4.0.
During my search on this topic I came across CocoaOniguruma which uses Oniguruma, the Regular Expression engine behind Ruby1.9 and PHP5. It seems a bit newer compared to the existing OregKit (in Japanese). Not sure how these stack up against other bindings.
Googling alittle, found this library:
RegexOnNSString
Open source library, containing functions like:
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement caseInsensitive:(BOOL)ignoreCase
and using NSRegularExpression class. Quite easy to use and no need to worry about anything.
Please, note that NSRegularExpression is available since Mac OS X v10.7 and IOS 4.0, as Datasmid mentioned.
I make it easy. I add a new C++ file to my Objective C project, rename it as .mm, and then create a standard C++ class inside. Then, I make a static class method in the "public:" section for a C++ function that takes an NSString and returns an NSString (or NSArray, if that's what you want). I then convert NSString to C++ std::string like so:
// If anyone knows a more efficient way, let me know in the comments.
// The "if" condition below is because ObjC crashes if converting to
// std::string if the string is nil or empty.
// assume #include <string>
std::string s = "";
if (([sInput != nil]) && (!([sInput isEqualTo:#""]))) {
std::string sTemp([sInput UTF8String]);
s = sTemp;
}
From there, I can use regex_replace like so:
// assume #include <regex>
std::string sResult = std::regex_replace(sSource,sRegExp,sReplaceWith);
Then, I can convert that std::string back into an NSString with:
NSString *sResponse2 = #(sResult.c_str());
If you're only using this C++ just for this function, then you may find it suitable to call this file extra.mm (class name Extra) and put this static class method in, and then add other static class methods when the situation arrives where it just makes sense to do it in C++ because it's less hassle in some cases. (There are cases where ObjC does something with less lines of code, and some cases where C++ does it with less lines of code.)
P.S. Still yet another way with this is to use a .mm file but make an Objective C wrapper around the use of std::string and std::regex_replace() (or regex_match()).