I'm quite new to haskell and not too comfortable with it's type system yet. And I wondering, if there is ability to define the type (datatype?), which instances can be called as functions?
Analogues are
__call__
method in Python or class method
operator()
in c++. (More examples are given in wikipedia for the word "Function object").
The example of application of such a construct is Polynom. The object is defined by list of its coefficients, i.e. I would like to have type like this:
data Num a => Polynom a = Polynom [a]
deriving (...)
Now of course I can define function
callPoly :: Num a => (Polynom a) -> a -> a
callPoly p x = ... -- implementation: extract coefficients of p,
-- construct polynomial and call it on x
(here I do not bother, to be able to call polynom with Int coefficients on Floats... it's just techincal details)
Now I can call it on my polinomial (in interactive prompt):
let myPoly = Polynomial [1 2 3]
let applicationResult = callPoly myPoly 3
But this way is not too fancy. Is is desirable to be able to call polynomial directly as
let applicationResult = myPoly 3
So the question is: It is possible to define such Polynomial type, which objects (instances) can be called (used as functions)? May be this pattern may be implemented in some other way, not involving 'data'? May be some playing with function types or smth. else?
Of course, this idea can be applied not only to polynomials. Actually, to any function, which must "has type" and has "some attached data" (in case of polynomial - it is coefficients).
Or if this is not possible, then is there some specific reason for this or it is just not supported?
P.S.: It seems to me, that direct approach (as described above) is impossible, because to be callable myPoly must be of type (Int -> Int). But type (Int -> Int) cannot have any data attached (i.g. polynomial coefficients). But I want to make sure, that I'm right.
let myPoly = callPoly (Polynomial [1, 2, 3])
? – Sjoerd Visscher[] ||| x = 0 ; (c :cs) ||| x = c + x * (cs ||| x)
Then inghci
you ask[1,2,3,4,5] ||| 3
and get547
as answer. – applicative