Reputation: 443
In java and c# we have interfaces, what is the equivalent to that in a language like haskell or what is the concept called in functional programming?
Upvotes: 4
Views: 3560
Reputation: 839
The function signature (the input and output types of your function) along with 2:nd order functions (functions that can be put in variables) take the role that an Interface has in object oriented languages. As long as the function signature matches the expected type, you can substitute one function for another.
For instance, assume a function f
that takes two arguments: An integer a
and a function g
, where the function argument g
should in turn be a function that takes an int
and returns a str
:
For example (in pseudocode for all that are curious about functional programming):
fun f(a: int, g:int->str) -> int
Just by declaring the parameter g
, you have now created an interface: You can only pass a function for the parameter g
that matches the signature of g
, but as long as you match that signature, you can pass any function.
Upvotes: 2
Reputation: 92117
There are things like typeclasses, as the other answers say, but even more than that, there's one pervasive interface: a function. Many, many places where an object-oriented program would need some custom interface, a similar functional program can just use a function. eg, map f xs
in haskell uses f
, where an object-oriented program might use a Strategy or whatever to accomplish the same task.
Upvotes: 13
Reputation: 34934
data and newtype in Haskell are approximately equal to class in Java.
class in Haskell is approximately equal to interface in Java.
Upvotes: -2
Reputation: 36385
Haskell typeclasses fulfill some of the same roles as interfaces in object oriented languages.
Upvotes: 7