首页 > 解决方案 > 负数不被视为 Int 吗?

问题描述

我是 Haskell 的新人。当我试图定义函数 ci 时,我得到了负参数的错误,有人可以向我解释为什么负数的处理方式不同吗?谢谢!

$ ghci
GHCi, version 8.10.7: https://www.haskell.org/ghc/  :? for help
> ci :: (Ord a, Num a) => a -> Int; ci x = if x < 0 then -1 else if x == 0 then 0 else 1
> ci 1
1
> ci 0
0
> ci -1

<interactive>:4:1: error:
    • Non type-variable argument in the constraint: Num (a -> Int)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall a. (Ord a, Num a, Num (a -> Int)) => a -> Int

根据错误消息,尝试设置 FlexibleContexts,但 GHCi 将结果 -1 视为函数?

> :set -XFlexibleContexts
> ci -1

<interactive>:6:1: error:
    • No instance for (Show (Integer -> Int))
        arising from a use of ‘print’
        (maybe you haven't applied a function to enough arguments?)
    • In a stmt of an interactive GHCi command: print it

标签: haskell

解决方案


推荐阅读