如何在使用GHCi时为函数提供显式类型声明? [英] How to provide explicit type declarations for functions when using GHCi?

查看:92
本文介绍了如何在使用GHCi时为函数提供显式类型声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在GHCi中定义此功能的等价物(取自 learnyouahaskell )?

  import Data.List 

numUniques ::(Eq a)=> [a] - > Int
numUniques = length。 nub

如果没有类型声明,GHCi会接受函数定义,但最终会出现无用的类型:

  Prelude Data.List> import Data.List 
Prelude Data.List>让numUniques'=长度。 nub
Prelude Data.List> :t numUniques'
numUniques':: [()] - > Int

结果函数只接受单位列表作为参数。



有没有办法在GHCi中提供类型声明?还是有另一种方式来定义这些不需要类型声明的函数?



我没有看到GHCi指南中的明显线索,并尝试使用类似以下的表达式(无效):

 >让numUniques'=((length.nub)::(等式a)=> [a]  - > Int)
> :t numUniques'
numUniques':: [()] - > Int


解决方案


在GHCi中提供类型声明?




  let numUniques'::(Eq a)=> ; [a]  - >诠释; numUniques'=长度。或者是否有另一种方法来定义类似这样的函数,它不会' t要求类型声明?

如果关闭 -XNoMonomorphismRestriction ,它会推断出正确的类型。


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

解决方案

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.

这篇关于如何在使用GHCi时为函数提供显式类型声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆