I have a parametric variable in a type class which I would like to represent any of the number types (Float, Integer, Double etc).
How I do declare this in the type and instance?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you mean the type parameter for the class itself, you can add a constraint to the context of the class definition:
On the other hand, if it’s a parameter in a function’s type that isn’t the class parameter, then you can add a constraint in the usual fashion:
If you want to constrain it to only certain specific types, that’s not really possible–type classes are “open”, i.e., you can always add instances. The best you could do is have your own class (
FooNumbersor such), write only the instances you want, and then require that instead ofNum. But that’s usually not helpful.