问题描述
为了尝试和练习一点haskell并了解免费点数,我正在玩一个函数来计算一个数字
所以我开始定义
>让dup fx = fxx
所以我可以用dup重写sq(不用担心现在可以免费使用dup点)
>让sq x = dup(*)x
并检查sq的类型,看看我期望看到什么
>:t sq
> sq :: Num t => t - > t
所以我删除了x并得到
> let sq = dup(*)
>:t sq
sq :: Integer - >整数
我缺少什么?
你遇到了单态限制。 Haskell不会推断函数的多态类型,除非它们是以函数风格给出的(不是免费的)。这意味着 let sq = dup(*)
不会键入check,但Haskell对于标准数字类有所谓的默认规则,这意味着它默认为单形类型`整数 - >整数
Prelude>:set -XNoMonomorphismRestriction
Prelude> let dup fx = fxx
Prelude> let sq = dup(*)
Prelude>:t sq
sq :: Num t => t - > t
To try and practice a bit of haskell and learn about point free I was playing around with a function to square a number
so I started by defining
>let dup f x = f x x
so I could rewrite sq in terms of dup (without worrying about making dup point free for now)
>let sq x = dup (*) x
and checking the type of sq I see what I'm expecting to see
>:t sq
>sq :: Num t => t -> t
so I remove the x's and get
>let sq = dup (*)
>:t sq
sq :: Integer -> Integer
what am I missing?
You have run into the monomorphism restriction. Haskell will not infer polymorphic types for functions unless they are given in "function" style (not point free). This would mean that let sq = dup (*)
would not type check, but Haskell has so called "default rules" for standard numeric classes that mean it defaults to the monomorphic type `Integer->Integer"
Prelude> :set -XNoMonomorphismRestriction
Prelude> let dup f x = f x x
Prelude> let sq = dup (*)
Prelude> :t sq
sq :: Num t => t -> t
这篇关于为什么要将sq改为无点改变类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!