Note that there are some explanatory texts on larger screens.

plurals
  1. POWriting A Function Polymorphic In A Type Family
    primarykey
    data
    text
    <p>I was experimenting with type families yesterday and ran into an obstacle with the following code:</p> <pre><code> {-# LANGUAGE TypeFamilies #-} class C a where type A a myLength :: A a -&gt; Int instance C String where type A String = [String] myLength = length instance C Int where type A Int = [Int] myLength = length main = let a1 = [1,2,3] a2 = ["hello","world"] in print (myLength a1) &gt;&gt; print (myLength a2) </code></pre> <p>Here I have a type associated with class C and a function that calculates the length of the associated type. However the above code gives me this error:</p> <pre><code> /tmp/type-families.hs:18:30: Couldn't match type `A a1' with `[a]' In the first argument of `myLength', namely `a1' In the first argument of `print', namely `(myLength a1)' In the first argument of `(&gt;&gt;)', namely `print (myLength a1)' /tmp/type-families.hs:19:30: Couldn't match type `A a2' with `[[Char]]' In the first argument of `myLength', namely `a2' In the first argument of `print', namely `(myLength a2)' In the second argument of `(&gt;&gt;)', namely `print (myLength a2)' Failed, modules loaded: none. </code></pre> <p>If, however I change "type" to "data" the code compiles and works:</p> <pre><code> {-# LANGUAGE TypeFamilies #-} class C a where data A a myLength :: A a -&gt; Int instance C String where data A String = S [String] myLength (S a) = length a instance C Int where data A Int = I [Int] myLength (I a) = length a main = let a1 = I [1,2,3] a2 = S ["hello","world"] in print (myLength a1) &gt;&gt; print (myLength a2) </code></pre> <p>Why does "length" not work as expected in the first case? The lines "type A String ..." and "type A Int ..." specify that the type "A a" is a list so myLength should have the following types respectively : "myLength :: [String] -> Int" or "myLength :: [Int] -> Int".</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.
    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