为什么我得到"没有(分数a0)..."的错误?

CYC*_*CYC 1 haskell types compiler-errors

键入时,以下代码不起作用test 10:

test m = if m `mod` 2==0
             then m/2
             else m
Run Code Online (Sandbox Code Playgroud)

它说如下:

No instance for (Fractional a0) arising from a use of ‘it’
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
  instance Integral a => Fractional (GHC.Real.Ratio a)
    -- Defined in ‘GHC.Real’
  instance Fractional Double -- Defined in ‘GHC.Float’
  instance Fractional Float -- Defined in ‘GHC.Float’
In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
Run Code Online (Sandbox Code Playgroud)

test n对于整数n,它可能是一些整数或双类型问题,但我不知道什么是错的.

mel*_*ene 7

问题是mod只适用于整数类型,但/仅适用于小数类型,因此无法实际使用您的test函数.

你可以这样做:

test m = if m `mod` 2 == 0
             then m `div` 2
             else m
Run Code Online (Sandbox Code Playgroud)

(div是整数除法.)

或这个:

test m | even m    = m `div` 2
       | otherwise = m
Run Code Online (Sandbox Code Playgroud)

或这个:

test m
    | (d, 0) <- m `divMod` 2 = d
    | otherwise              = m
Run Code Online (Sandbox Code Playgroud)