简体   繁体   English

使用算术类型函数在Haskell中编写函数

[英]Composing functions in Haskell with arithmetic-type functions

I'm learning Haskell now and I'm trying to play around with function composition. 我现在正在学习Haskell,我正在尝试使用函数组合。

I wrote two functions. 我写了两个函数。

let func1 xy = x + y

let func2 t = t*2

However, when I try to compose these two functions, func2 . func1 1 2 但是,当我尝试编写这两个函数时, func2 . func1 1 2 func2 . func1 1 2 I am expecting to get 6. func2 . func1 1 2我期待得到6分。

Instead, I get this error: 相反,我收到此错误:

   No instance for (Num (a -> b))
      arising from a use of `func1' at <interactive>:1:8-16
    Possible fix: add an instance declaration for (Num (a -> b))
    In the second argument of `(.)', namely `func1 1 2'
    In the expression: func2 . func1 1 2
    In the definition of `it': it = func2 . func1 1 2

Can someone explain why this is not working? 有人可以解释为什么这不起作用?

Function application has precedence over any operators, so your composition is parsed as func2 . (func1 1 2) 函数应用程序优先于任何运算符,因此您的组合被解析为func2 . (func1 1 2) func2 . (func1 1 2) . func2 . (func1 1 2) That is, your code tries to compose the number that's the result of func1 1 2 as if it was a function. 也就是说,您的代码尝试将func1 1 2的结果编号组成,就像它是一个函数一样。 Note that (func2 . func1) 1 2 doesn't work either, as (.) only works with unary functions. 请注意, (func2 . func1) 1 2也不起作用,因为(.)仅适用于一元函数。

You could use (func2 . func1 1) 2 , or use (.) multiple times in ways that I'm not very comfortable with personally, to tell the truth. 可以使用(func2 . func1 1) 2 ,或者以我个人不太熟悉的方式多次使用(.)实话。 But it's probably better to not use composition at all in this specific case: func2 $ func1 1 2 does the same thing with less clutter. 但是在这种特殊情况下根本不使用合成可能更好: func2 $ func1 1 2做同样的事情而且杂乱少。

Due to a lucky mistake (distributive law), you can do this with Data.Function.on 由于幸运的错误(分配法),您可以使用Data.Function.on执行此Data.Function.on

import Data.Function

func1 x y = x + y
func2 t = t*2

func3 = func1 `on` func2

-- or just func3 = (+) `on` (2*)

In general though, you should just use $ for this sort of thing, since that's what you're doing, function application. 一般来说,你应该只使用$来做这类事情,因为这就是你正在做的功能应用程序。 This isn't really a job for compose, so you're trying to jam a square peg into a round hole if you use composition. 这不是一个真正的作品,所以如果你使用作曲,那么你正试图将方形钉子塞进一个圆孔中。

你要做的不是函数组合:你试图将func1 1 2应用于func2 ,这就是$运算符的用途。

func2 $ func1 1 2

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

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