Skip to content

Instantly share code, notes, and snippets.

@pjrt
Created October 20, 2014 22:03
Show Gist options
  • Select an option

  • Save pjrt/d2c2339e5bc0c93f6e23 to your computer and use it in GitHub Desktop.

Select an option

Save pjrt/d2c2339e5bc0c93f6e23 to your computer and use it in GitHub Desktop.
Returning functions and values restricted by typeclasses
class Writable a where
write :: a -> String
data Box = Box String
data Hax = Hax String
instance Writable Hax where
write (Hax str) = str
instance Writable Box where
write (Box str) = str
func :: Writable a => Int -> (a -> String, a)
func compare = if compare > 0
then (write, Box (show compare))
else (write, Hax (show compare))
main = do
let (f, v) = func 1
putStrLn $ f v
@pjrt
Copy link
Copy Markdown
Author

pjrt commented Oct 22, 2014

Doesn't work. Error is:

haskell.hs:15:29:
    Could not deduce (a ~ Box)
    from the context (Writable a)
      bound by the type signature for
                 func :: Writable a => Int -> (a -> String, a)
      at haskell.hs:13:9-45
      ‘a’ is a rigid type variable bound by
          the type signature for
            func :: Writable a => Int -> (a -> String, a)
          at haskell.hs:13:9
    Relevant bindings include
      func :: Int -> (a -> String, a) (bound at haskell.hs:14:1)
    In the expression: Box (show compare)
    In the expression: (write, Box (show compare))

haskell.hs:19:16:
    No instance for (Writable t0) arising from a use of ‘func’
    The type variable ‘t0’ is ambiguous
    Relevant bindings include
      f :: t0 -> String (bound at haskell.hs:19:8)
      v :: t0 (bound at haskell.hs:19:11)
    Note: there are several potential instances:
      instance Writable Box -- Defined at haskell.hs:10:10
      instance Writable Hax -- Defined at haskell.hs:7:10
    In the expression: func 1
    In a pattern binding: (f, v) = func 1
    In the expression:
      do { let (f, v) = func 1;
           putStrLn $ f v }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment