The Problem
I want to be able to create 2 data types
: A
and B
and to create 2 functions f
:
f :: A -> Int -> Int
f :: B -> String -> String -> String
The only way I can do it (so far as I know) is to use type classes
and instances
.
The problem is, that I do not want to explicit write f
signatures - I want type checker to infer it for me. Is it possible?
Example code
{-# LANGUAGE FlexibleInstances, FunctionalDependencies, UndecidableInstances #-}
data A = A{ax::Int} deriving(Show)
data B = B{bx::Int} deriving(Show)
data C = C{cx::Int} deriving(Show)
-- I don't want to explicit say the signature is Int->Int
-- I would love to write:
-- instance Func_f A (a->b) where
instance Func_f A (Int->Int) where
f _ i = i*2
-- I don't want to explicit say the signature is String->String->String
-- I would love to write:
-- instance Func_f B (a->b->c) where
instance Func_f B (String->String->String) where
f _ s1 s2 = "test"++s1++s2
-- I don't want to explicit say the signature is a->a
-- I would love to write:
-- instance Func_f C (a->b) where
instance Func_f C (a->a) where
f _ i = i
class Func_f a b | a -> b where
f :: a -> b
f2 _ s1 s2 = "test"++s1++s2 -- Here the type inferencer automaticly recognizes the signature
main :: IO ()
main = do
let
a = A 1
b = B 2
c = C 3
a_out = f a 5
b_out = f b "a" "b"
c_out = c 6
print a_out
print b_out
print c_out
Explaination
I'm writing custom domain language compiler and I'm generating Haskell code as a result. I don't want the final users of my language write explicit types, so I want to use Haskells powerful type system to infer as much as possible.
If I write function like f2 _ s1 s2 = "test"++s1++s2
I do not have to explicit write its signature - because compiler can infer it. Can we somehow ask compiler to infer the signatures of f
in the above example?
I would love to know every possible "hack" to solve this problem, even if this hack would be "ugly", because I'm generating Haskell code and it does not have to be "pretty".