Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this simple type definition? (Expecting one more argument to...)

Tags:

haskell

basic.hs:

areaCircle :: Floating -> Floating
areaCircle r = pi * r * r

Command:

*Main> :l basic.hs 
[1 of 1] Compiling Main             ( Sheet1.hs, interpreted )

Sheet1.hs:2:15:
    Expecting one more argument to `Floating'
    In the type signature for `areaCircle':
      areaCircle :: Floating -> Floating
Failed, modules loaded: none.

I see that areaCircle :: Floating a => a -> a loads as expected. Why is the above version not acceptable?

like image 451
8128 Avatar asked Oct 15 '12 21:10

8128


People also ask

What is the type of a function Haskell?

Haskell has first-class functions : functions are values just like integers, lists, etc. They can be passed as arguments, assigned names, etc. … val is value of type Int , and half_of is a value of type Float -> Float .

What is type checking in Haskell?

Haskell uses a system of static type checking. This means that every expression in Haskell is assigned a type.

What is composite data type in Haskell?

A composite data type is constructed from other types. The most common composite data types in Haskell are lists and tuples.


2 Answers

Because your version does not actually supply a type. Floating is a type class. If you want to allow any Floating, then Floating a => a -> a is correct. Otherwise you can try either Float -> Float or Double -> Double.

Just to flesh it out a bit more: Floating a => a -> a says not only that your function accepts any Floating type, but that it returns the same type it is passed. This must be true even if you narrow the type. For example, you would not be able to use Float -> Double without doing some additional conversions

like image 168
Dan Avatar answered Jan 30 '23 05:01

Dan


Floating isn't a type, it's a type class. You can't use a type class as a type like you are. When you say Floating in Haskell you're asserting that the following type is an instance of the class. So, for example, you could write the code as

areaCircle :: Floating a => a -> a
areaCircle r = pi * r * r

which you can read informally as: for any type a, if a is an instance of the class Floating then areaCircle can be used as a function from a to a.

You can think of Floating as a bit like an adjective. It describes types. But you're trying to use it like a noun, ie. as a type itself.

http://en.wikipedia.org/wiki/Type_class

like image 43
sigfpe Avatar answered Jan 30 '23 05:01

sigfpe