1

I have defined the following function addtofour:

addtofour :: Int -> Int
addtofour x = 4 + x

When I load this into ghci this works fine. However, when I try to concatenate it with a value returned by LogBase, it won't work.

I tried:

logbase 2 3 -- returns 1.58..
addtofour logBase 2 3 -- error, expected 1.58 + 4 = 5.58
addtofour (logBase 2 3) -- error, expected 1.58 + 4 = 5.58

I expect logBase 2 3 to return an Int, which I can then put into my addtofour function. But this somehow fails. I guess it has to do with the domain of my addtofour function. But why would I have to change that? f(x) = 4+x does Int -> Int

4
  • 2
    You expect logBase 2 3 to return an Int, even though logbase 2 3 // returns 1.58..? Commented Apr 23, 2020 at 14:10
  • Wow, I am embarrassed. Float -> Float fixes things Commented Apr 23, 2020 at 14:12
  • 2
    Try to keep your functions as general as possible. addtofour :: Num a => a -> a lets you add 4 to a value of any numeric type (since 4 itself has type Num a => a). Commented Apr 23, 2020 at 14:29
  • I'm glad you solved this. For future posts, please cut & paste the error in the question instead of simply writing "I get an error here". Without the error text, it is harder for us to understand what's the issue, since we have to type-check your code in our head. Commented Apr 23, 2020 at 16:58

1 Answer 1

4

logBase is returning 1.58, which is not an Int. Your addtofour function only accepts Ints. You can fix this by making the type of addtofour generic:

addtofour :: Num a => a -> a

Your second case will still fail, though:

addtofour logBase 2 3

This is because it tries to pass logBase as the argument to addtofour. You either need parentheses to clarify the order of application:

addtofour (logBase 2 3)

or the ($) operator, which has right-precedence.

addtofour $ logBase 2 3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.