def f(x, y):
return x & 1 == 0 and y > 0
g = lambda x, y: x & 1 == 0 and y > 0
现在哈斯凯尔也发生了同样的事情:
import Data.Bits
f :: Int -> Int -> Bool
f x y = (.&.) x 1 == 0 && y > 0
这是可行的,但这不可行:
g = \x y -> (.&.) x 1 == 0 && y > 0
这是一个错误:
someFunc :: IO ()
someFunc = putStrLn $ "f 5 7: " ++ ( show $ f 5 7 ) ++ "\tg 5 7: " ++ ( show $ g 5 7 )
• Ambiguous type variable ‘a0’ arising from the literal ‘1’
prevents the constraint ‘(Num a0)’ from being solved.
Relevant bindings include
x :: a0 (bound at src/Lib.hs:13:6)
g :: a0 -> Integer -> Bool (bound at src/Lib.hs:13:1)
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
instance Num Float -- Defined in ‘GHC.Float’
...plus two others
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the second argument of ‘(.&.)’, namely ‘1’
In the first argument of ‘(==)’, namely ‘(.&.) x 1’
In the first argument of ‘(&&)’, namely ‘(.&.) x 1 == 0’
|
13 | g = \x y -> (.&.) x 1 == 0 && y > 0
| ^
如何在Python中获得相同的错误?-当输入与预期不匹配时,我如何获得错误
具体来说,我如何说函数/lambda必须具有:
__matmul__
(@
)bool
我知道我可以用:(docstrings和/或PEP484)和abc
大致做到这一点;上课。但对于模块中的“松散”函数,我能做些什么
通常有三种可能的方法:
1 + 'foo'
是TypeError
)李>你的具体观点:
定义五个参数:
静态类型批注之一:
和/或运行时检查:
assert
用于调试目的,可以禁用,而显式if..raise
则不能。考虑到这种方法的冗长性和duck类型哲学,这些方法并不是很像python如果传递的值不支持该操作,最实用的方法可能是让运行时在本质上引发错误,即只执行以下操作:
如果要对此进行静态类型检查,可以使用
typing.Protocol
:在实践中,您可能希望将其与前面的“每个参数都必须是数字”和类型提示结合起来,以获得满足这两个要求的类型
特别是考虑到
@
运算符主要由第三方软件包(如numpy)使用,在实践中,此类函数最具python风格的实现可能是以下几点:您不能直接将相同的类型期望从Haskell转换为Python。Haskell是一种疯狂的强类型语言,而Python则几乎完全相反
要键入接受此类函数作为参数的高阶函数,请使用
typing.Callable
:相关问题 更多 >
编程相关推荐