Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide explicit type declarations for functions when using GHCi?

How to I define the equivalent of this function (taken from learnyouahaskell) inside GHCi?

import Data.List    numUniques :: (Eq a) => [a] -> Int   numUniques = length . nub   

Without the type declaration, GHCi accepts the function definition, but it ends up with an unhelpful type:

Prelude Data.List> import Data.List  Prelude Data.List> let numUniques' = length . nub Prelude Data.List> :t numUniques' numUniques' :: [()] -> Int 

The resulting function only accepts a list of units as a parameter.

Is there a way provide type declarations in GHCi? Or is there another way to define functions like these which doesn't require type declarations?

I saw no obvious clues in the GHCi guide, and experimented with expressions like the following (to no avail):

> let numUniques' = ((length . nub) :: (Eq a) => [a] -> Int) > :t numUniques' numUniques' :: [()] -> Int 
like image 399
mattbh Avatar asked Jun 22 '10 12:06

mattbh


People also ask

What is function declaration Haskell?

Like other languages, Haskell does have its own functional definition and declaration. Function declaration consists of the function name and its argument list along with its output. Function definition is where you actually define a function.

What is a type signature Haskell?

From HaskellWiki. A type signature is a line like. inc :: Num a => a -> a. that tells, what is the type of a variable. In the example inc is the variable, Num a => is the context and a -> a is its type, namely a function type with the kind * -> * .

What is type in Haskell?

In Haskell, every statement is considered as a mathematical expression and the category of this expression is called as a Type. You can say that "Type" is the data type of the expression used at compile time. To learn more about the Type, we will use the ":t" command.


2 Answers

Is there a way provide type declarations in GHCi?

let numUniques' :: (Eq a) => [a] -> Int; numUniques' = length . nub 

Or is there another way to define functions like these which doesn't require type declarations?

If you turn off the monomorphism restriction with -XNoMonomorphismRestriction, it will infer the right type.

like image 60
sepp2k Avatar answered Oct 07 '22 06:10

sepp2k


Note that you can also avoid the monomorphism restriction simply by adding "points" (i.e. explicit variables) back to your expression. So this also gives the correct type:

let numUniques x = length . nub $ x

like image 43
sclv Avatar answered Oct 07 '22 06:10

sclv