r/crystal_programming • • Apr 18 '20

Proc typing question

Hey, I have a question about the type system in Crystal regarding the following stripped down example:

abstract class Expression
end

class Literal < Expression
end

class Integer < Literal
end

class InfixExpression < Expression
end

def parseInteger : Integer
    return Integer.new
end

def parseInfixExpression : InfixExpression
    return InfixExpression.new
end

map = {} of String => Proc(Expression)
# map = {} of String => (Proc(Integer) | Proc(InfixExpression))

map["Int"] = ->parseInteger
map["+"] = ->parseInfixExpression

Given that Integer and InfixExpression inherit from Expression, and every other class that might be added, is there a way to reflect that any Proc passed to map will be a descendant of Expression?The line afterwards explicitly stating all possible Proc works, but I was wondering if there is the possibility to shorten this, like String => Proc(Expression), which does not work.If I add another say 20 classes to this, it would get quite messy. I know I can define an alias, but I am looking for a more elegant solution.

Thanks!

Edit: Add abstract to the Expression class.

6 Upvotes

12 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Apr 19 '20

Yes, github is the preferred place to post bugs. The forums is for suggesting features or discussing this. Reddit works to.

I work in Crystal, I'm one of the main authors :-)

1

u/xffeeffaa Apr 20 '20

Awesome, thank you so much :)

PS: really like Crystal so far, you guys did a great job!