[Haskell-beginners] type class functions as function arguments

Christopher Howard christopher.howard at frigidcode.com
Fri Sep 14 05:23:50 CEST 2012

In my app, I am trying to save a whole bunch of code duplication by
leverage the fact that functions can be passed in to other functions as
arguments. However, I run into a kink when I try to use functions from
type classes, and then apply those functions to different types of
arguments after the functions have been passed in.

My actual code is rather long and somewhat complicated, so I will use
this simpler example: Obviously both the following functions work fine:

g :: (Integer, Double)
g = ((+) 1 2, (+) 2.0 3.0)

g' :: (Integer, Double)
g' = ((-) 1 2, (-) 2.0 3.0)

*Main> g
*Main> g'

However, what if I want to create a single function, where I just pass
in the (+) or the (-) function? I not sure the right way to do that,
exactly, but I tried something like this:

gCore :: Num a => (a -> a -> a) -> (Integer, Double)
gCore f = (f 1 2, f 2.0 3.0)

The resulting error is:

    Couldn't match type `Double' with `Integer'
    In the return type of a call of `f'
    In the expression: f 1 2
    In the expression: (f 1 2, f 2.0 3.0)

It is as though the function "forgot" that it could be used on different
types, and just picked one, and now is complaining that is being used
with the wrong type in the other case.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 551 bytes
Desc: OpenPGP digital signature
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120913/9e9e79df/attachment.pgp>

More information about the Beginners mailing list