gpt4 book ai didi

Haskell:用两个 float 参数组合函数失败

转载 作者:行者123 更新时间:2023-12-04 13:12:23 24 4
gpt4 key购买 nike

我正在尝试编写 (Floating a) => a -> a -> a 类型的函数具有 (Floating a) => a -> a 类型的函数获得 (Floating a) => a -> a -> a 类型的函数.我有以下代码:

test1 :: (Floating a) => a -> a -> a
test1 x y = x

test2 :: (Floating a) => a -> a
test2 x = x

testBoth :: (Floating a) => a -> a -> a
testBoth = test2 . test1
--testBoth x y = test2 (test1 x y)

但是,当我在 GHCI 中编译它时,出现以下错误:
/path/test.hs:8:11:
Could not deduce (Floating (a -> a)) from the context (Floating a)
arising from a use of `test2'
at /path/test.hs:8:11-15
Possible fix:
add (Floating (a -> a)) to the context of
the type signature for `testBoth'
or add an instance declaration for (Floating (a -> a))
In the first argument of `(.)', namely `test2'
In the expression: test2 . test1
In the definition of `testBoth': testBoth = test2 . test1
Failed, modules loaded: none.

注意 testBoth 的注释掉的版本编译。奇怪的是,如果我删除 (Floating a)所有类型签名的约束或如果我更改 test1就拿 x而不是 xy , testBoth编译。

我搜索了 StackOverflow、Haskell wikis、Google 等,但没有发现任何与此特定情况相关的函数组合限制。有谁知道为什么会这样?

最佳答案

   \x y -> test2 (test1 x y)
== \x y -> test2 ((test1 x) y)
== \x y -> (test2 . (test1 x)) y
== \x -> test2 . (test1 x)
== \x -> (test2 .) (test1 x)
== \x -> ((test2 .) . test1) x
== (test2 .) . test1

这两件事彼此不一样。
   test2 . test1
== \x -> (test2 . test1) x
== \x -> test2 (test1 x)
== \x y -> (test2 (test1 x)) y
== \x y -> test2 (test1 x) y

关于Haskell:用两个 float 参数组合函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4340992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com