Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Haskell: Defining function types..

  • 08-10-2009 08:20PM
    #1
    Registered Users, Registered Users 2 Posts: 2,238 ✭✭✭


    Hi There,

    I'm pretty new to Haskell atm. I'm struggling with most things but one thing I can't get my head around is defining function types. I can define a function like so: sum a b = a+b and it works fine.

    Why must we define/declare/type [??] the function beforehand like so:
    sum :: Integer->Integer->Integer

    This above example works with or without the type declaration but I am having trouble with making a function that takes in integers and returns a float.
    How do I get the following to return a float?
    sum :: Integer->Integer->???
    sum a b = 2.0*(a+b)
    

    If I change ??? to Integer I get the error "Instance of Fractional Integer required for definition of sum"

    If I change it to Float I get the error "Type error in explicitly typed binding"

    Any ideas?Thanks..!


Comments

  • Registered Users, Registered Users 2 Posts: 1,924 ✭✭✭ronivek


    sum :: (Fractional a) => a -> a -> a

    That should work fine; it just needed to be bumped up a level of abstraction basically. Now it will work for all numbers that can be represented fractionally.


  • Registered Users, Registered Users 2 Posts: 2,238 ✭✭✭techguy


    Cool, thanks i'll give that a go


Advertisement
Advertisement