Haskell:默认的类型限制 [英] Haskell: Defaulting constraints to type
问题描述
考虑这个例子:
applyKTimes :: Integral i =>我 - > (a - > a) - > a - > a
applyKTimes 0 _ x = x
applyKTimes k f x = applyKTimes(k-1)f(f x)
applyThrice ::(a - > a) - > a - > a
applyThrice = applyKTimes 3
3
中的 applyThrice
由GHC默认为整数
,与编译时显示的一样。 Wall
:
警告:默认以下约束来输入'Integer'
'使用'applyKTimes'
引起的'积分t'
所以我猜整数
是默认的 Integral a => a
。
- 有没有办法为其他约束定义默认类型?
- 使用默认类型的错误练习? (它使用
-Wall
..时抱怨)
解决方案是的,你可以,虽然它不是非常简单,只需添加一个默认的每种类型类型,它只适用于
Num
及其在Prelude
中的子类以及标准库。语法是default(t1,...,tn)
,并且每个模块只能使用一个这样的声明。
例如,添加default(Int)
会将代码中的Integral
的默认值更改为Int
。
默认默认为
(整数,双精度)
不仅仅是GHC政策:它来自 Haskell 98报告。 (GHCi确实有扩展默认规则)。
这里是讨论当前系统的一些问题。
Consider this example:
applyKTimes :: Integral i => i -> (a -> a) -> a -> a applyKTimes 0 _ x = x applyKTimes k f x = applyKTimes (k-1) f (f x) applyThrice :: (a -> a) -> a -> a applyThrice = applyKTimes 3
The
3
inapplyThrice
is defaulted by GHC to anInteger
as shown when compiling with-Wall
:Warning: Defaulting the following constraint(s) to type 'Integer' 'Integral t' arising from a use of 'applyKTimes'
So I guess that
Integer
is the defaultIntegral a => a
.- Is there a way to define "default types" for other constraints too?
- Is using default types bad practice? (it does complain when using
-Wall
..)
解决方案Yes, you can, although it's not quite so simple as adding a default per typeclass, and it only works for
Num
and its subclasses in thePrelude
and standard libraries. The syntax isdefault (t1, ..., tn)
, and only one such declaration can be used per module.Adding
default (Int)
, for example, would change the default forIntegral
in your code toInt
.The default default of
(Integer, Double)
isn't just a GHC policy: it's from the Haskell 98 Report. (GHCi does have extended default rules, though.)Here's a discussion of some of the problems with the current system.
这篇关于Haskell:默认的类型限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!