0

I'm new to haskell, and i'm trying to use operand .

function strangeMaths has to be smth like logBase 2 ((max x)^3) but using 3 functions and operand . so i did this code

strangeMaths = f . g . h

f = logBase 2 

g = (^3)

h = max

but this gives me an error:

No instance for (Ord a0) arising from a use of `max'
    The type variable `a0' is ambiguous
    Relevant bindings include
      h :: a0 -> a0 -> a0 (bound at 14)doItYourSelf.hs:7:1)
    Note: there are several potential instances:
      instance Integral a => Ord (GHC.Real.Ratio a)
        -- Defined in `GHC.Real'
      instance Ord () -- Defined in `GHC.Classes'
      instance (Ord a, Ord b) => Ord (a, b) -- Defined in `GHC.Classes'
      ...plus 23 others
    In the expression: max
    In an equation for `h': h = max
Failed, modules loaded: none.

P.S. i know that log (a, b^c) = c*log (a, b) but this is an example.

AJF
  • 11,767
  • 2
  • 37
  • 64

1 Answers1

3

Your problem is that max takes two arguments, not one.

Let's inspect the signature of .:

(.) :: (b -> c) -> (a -> b) -> (a -> c)

We clearly see that these take functions that take one argument and 'chain' them together.

Now let's have a look at max:

max :: (Ord a) => a -> a -> a

This is a function that takes two arguments, or in other words takes one argument, then returns another function. So, for instance, max 1 :: Int -> Int.

Now let's take a look at g . h, a part of the function you're trying to write:

  f . g
= (^2) . max
= \a -> (max a)^2

Then we have a problem: max a is a function, not a floating point value. Hence the compiler complains. This is equivalent to trying to compute map^2 or reverse^2; it's completely nonsensical.


Unfortunately you have not stated what strangeMaths should actually do, so I can't tell you how you should write it. However, there are a few ways to solve the issue:

  • Rewrite h as max 1 (instead of max), or some other similar value.
  • Rewrite strangeMaths as (.) (f . g) . h.
  • Write a Floating instance for functions of the form a -> a. (I don't know how or why you would do this, but it's possible.)

I suspect that the second case is true, as this would mean that strangeMaths x y = logBase 2 ((max x y)^2), which makes a lot more sense.

AJF
  • 11,767
  • 2
  • 37
  • 64