Why does changing sq to point-free change the type [duplicate]

不打扰是莪最后的温柔 提交于 2019-12-11 02:23:23

问题


Possible Duplicate:
What is going on with the types in this ghci session?

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?


回答1:


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


来源:https://stackoverflow.com/questions/11336031/why-does-changing-sq-to-point-free-change-the-type

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