포인트 프리 스타일로 함수를 변환하는 것은 해당 유형을 변경합니다.

StackOverflow https://stackoverflow.com/questions/6052670

문제

나는 Haskell을 시작합니다 ... 나는 Haskell이 유형을 결정하며, 유형 시스템이 각각의 경우마다 다른 유형을 두 가지 다른 방법으로 쓰려고 노력했습니다.그 행동에 대한 설명은 무엇입니까?

Prelude> let f x = 2 * x
Prelude> let g = (2*)
Prelude> :info f
f :: Num a => a -> a    -- Defined at <interactive>:1:5
Prelude> :info g
g :: Integer -> Integer     -- Defined at <interactive>:1:5
.

감사합니다!

도움이 되었습니까?

해결책

This is known as the monomorphism restriction.

Basically, it means that top-level bindings that look like x = are forced to be non-polymorphic, unless you specify a type signature. Bindings with arguments, i.e. f x = are not affected. See the link for details as to why this restriction exists.

Usually, you get an error message when the restriction is applied, but in this case GHCi is able to use type defaulting to change the type Num a => a to Integer.

The easiest way to dodge it is to either use an explicit type signature, or put

{-# LANGUAGE NoMonomorphismRestriction #-}

at the top of your module, or run GHCi with -XNoMonomorphismRestriction.

다른 팁

As others have pointed out, this is caused by something called the "Monomorphism Restriction".

MR can be useful for writers of Haskell compilers, and there is controversy about whether or not it is worthwhile to have in the language in general. But there is one thing everyone agrees: at the GHCi prompt, MR is nothing but a nuisance.

MR will probably be turned off by default in this context in an upcoming version of GHC. For now, you should disable it in GHCi by creating a text file called ".ghci" in your home directory that contains a line like this:

:set -XNoMonomorphismRestriction

Because the definition of g doesn't explicitly name its arguments, you run into the monomorphism restriction, preventing g from being polymorphic and (in this case) causing GHC to default to Integer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top