Haskell:默认的类型限制 [英] Haskell: Defaulting constraints to type

查看:175
本文介绍了Haskell:默认的类型限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:

  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 in applyThrice is defaulted by GHC to an Integer 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 default Integral 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 the Prelude and standard libraries. The syntax is default (t1, ..., tn), and only one such declaration can be used per module.

    Adding default (Int), for example, would change the default for Integral in your code to Int.

    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屋!

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