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

随声附和 提交于 2019-12-18 10:27:25

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3093133/how-to-provide-explicit-type-declarations-for-functions-when-using-ghci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!