Note that there are some explanatory texts on larger screens.

plurals
  1. POType inference of instance functions
    primarykey
    data
    text
    <p><strong>The Problem</strong></p> <p>I want to be able to create 2 <code>data types</code>: <code>A</code> and <code>B</code> and to create 2 functions <code>f</code>:</p> <ul> <li><code>f :: A -&gt; Int -&gt; Int</code></li> <li><code>f :: B -&gt; String -&gt; String -&gt; String</code></li> </ul> <p>The only way I can do it (so far as I know) is to use <code>type classes</code> and <code>instances</code>.</p> <p>The problem is, that I do not want to explicit write <code>f</code> signatures - I want type checker to infer it for me. Is it possible?</p> <p><strong>Example code</strong></p> <pre><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-&gt;Int -- I would love to write: -- instance Func_f A (a-&gt;b) where instance Func_f A (Int-&gt;Int) where f _ i = i*2 -- I don't want to explicit say the signature is String-&gt;String-&gt;String -- I would love to write: -- instance Func_f B (a-&gt;b-&gt;c) where instance Func_f B (String-&gt;String-&gt;String) where f _ s1 s2 = "test"++s1++s2 -- I don't want to explicit say the signature is a-&gt;a -- I would love to write: -- instance Func_f C (a-&gt;b) where instance Func_f C (a-&gt;a) where f _ i = i class Func_f a b | a -&gt; b where f :: a -&gt; 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 </code></pre> <p><strong>Explaination</strong></p> <p>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.</p> <p>If I write function like <code>f2 _ s1 s2 = "test"++s1++s2</code> I do <strong>not</strong> have to explicit write its signature - because compiler can infer it. Can we somehow ask compiler to infer the signatures of <code>f</code> in the above example?</p> <p>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".</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload