简体   繁体   English

Haskell function型

[英]Haskell function type

I'm trying to understand Haskell function types right now.我现在正在尝试了解 Haskell function 类型。 Let's say I want to compose two functions f1 and f2 (suppose I don't know their definition).假设我想组合两个函数 f1 和 f2(假设我不知道它们的定义)。 The function signature of f2. f2 的 function 签名。 f1 is: f1 是:

f1 . f2 :: (Fractional (a -> a), Num a) => a -> (a -> a) -> a -> a

How do I read this signature and more specifically, how do I know how to apply arguments to this composition?我如何阅读此签名,更具体地说,我如何知道如何将 arguments 应用于此组合?

eg how can I read the type information of f1.例如,我如何读取 f1 的类型信息。 f2 to be able to write valid expressions like f2 能够编写有效的表达式,例如

(f1 . f2 2) 3 4
(f1 2. f2 2) 4

That signature means you haven't composed them correctly.该签名意味着您没有正确组合它们。 You don't get a type error , because in theory some madman might give functions a Num instance, but in real life that never happens.您不会收到类型错误,因为理论上某些疯子可能会给函数一个 Num 实例,但在现实生活中这永远不会发生。 So there is no set of arguments you can apply to (f1. f2) that will typecheck.因此,没有一组 arguments 可以应用于(f1. f2)来进行类型检查。

Instead, back up and look at the types of f1 and f2 .相反,备份并查看f1f2的类型。 What are they?这些是什么? I predict that they are both two-argument functions, because your type is the one I get when I write我预测它们都是双参数函数,因为你的类型是我写的时候得到的类型

:t (/) . (+)
(/) . (+)
  :: (Fractional (a -> a), Num a) => a -> (a -> a) -> a -> a

You can't really compose a two-argument function, because composition is for one-argument functions.你不能真正组合一个有两个参数的 function,因为组合是针对一个参数的函数。 But you can partially apply the functions before composing, if you like, to make them into one-argument functions.但是,如果您愿意,您可以在组合之前部分应用这些函数,以将它们变成单参数函数。 And that's exactly what you've done in your last example, which works fine:这正是您在上一个示例中所做的,效果很好:

Prelude> f1 = (/)
Prelude> f2 = (+)
Prelude> (f1 2 . f2 2) 4
0.3333333333333333

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM