-
Notifications
You must be signed in to change notification settings - Fork 0
Type system
Firefly have a hybrid type system, also the language have implicit types.
fun parseInput(input) {
for(c : input.chars) {
if (c == '-')
parseOption(for.next())
}
}
fun parseOption(option) {
if (option == 'd')
this.debug = true
}
The compiler will infer CharSequence type to input argument and infer Char to option argument. The code above is equal to:
fun parseInput(input: CharSequence) {
for(c : input.chars) {
if (c == '-')
parseOption(for.next())
}
}
fun parseOption(option: Char) {
if (option == 'd')
this.debug = true
}
Like the loop? read about loops here.
Another example of the type inference firefly provides is this one:
fn add(a, b) {
return a + b
}
The code above is the same as:
fn <T: Add> add(a: T, b: T) {
return a + b
}
Add is the trait corresponding to + operator, any value that the type overloads the + operator (by implementing the Add trait) can be used as arguments of this function.
We can go a bit further in the type inference and look at this two examples:
fn addMul(a, b) {
return (a + b) * (b - a)
}
fn add2(a, b) {
return (a + b + 2)
}
The first one is the same as declaring fn <T: Add + Mul + Sub>(a: T, b: T), but the second one is more interesting. In order to this code work, the type of value b must implement Add<Int> trait, and the code is similar to this one:
fn <A: Add<B>, B: Add<Int>> add2(a: A, b: B) {
return (a + b + 2)
}
But not let's talk about this one:
fn add2Mul(a, b) {
return (a + b + 2) * (b - a)
}
Which corresponds to:
fn <A: Add<B>, B: Add<Int, U> + Sub<A, X>, U: Mul<X>, X> add2Mul(a, b) {
return (a + b + 2) * (b - a)
}
Lets break down the expression:
Expression: (a + b + 2) * (b - a)
Step 1: (a + b) -> B
Step 2: (b + 2) -> U
Step 3: (b - a) -> X
Step 4: (U * X) -> U
When the right side of the operator trait is absent, it defaults to the left side, so Add<B> corresponds to ? + B -> B, while Add<B, Y> corresponds to ? + B -> Y.
TODO
TODO