Haskell - 如何写(。)f f =(\ x - > f(f x)) [英] Haskell - How to write (.) f f = (\x -> f (f x))

查看:183
本文介绍了Haskell - 如何写(。)f f =(\ x - > f(f x))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在GHCi上运行的模块上编写一个功能组合函数。这(经典的 fog(x)= f(g(x)))运行:

 <.c $ c>(。)fg =(\ x  - > f(gx))。 

当我尝试像这样写这个问题时出现问题

 (。)ff =(\ x  - > f(fx))。 (fof(x)= f(f(x)))

GHCi说:

 f'的冲突定义
绑定在:Lab1.hs:27:9
Lab1.hs:27 :12

第27行:第9行出现,第27行:第27行再次出现f 。

为什么Haskell不能理解(。)ff =(\ x - > f(fx))

  foo xy = ... === foo =(\x->(\y- > ...))

如果 y 替换为 x ,第二个 x 只会影响中的第一个。 .. body:没有办法从那里引用第一个 x



您可以定义两次fx = f(fx)

lockquote
前奏曲>:t两次

两次::(t - > t) - > t - > t

前奏>两次(+1)4

6







另外, f(fx)=(。)ffx = join(。)fx


Prelude Control.Monad>:t join(。)

加入(。)::(b - > b) - > b - > b


join Control.Monad 中定义。对于函数,它认为加入g x = g x x 。它也被称为 W combinator

例如 print $ join(。)(+1)4 prints 6 a>。


I need to write on a module to be run on GHCi, with a function composition to the same function. This (The classic fog(x) = f(g(x))) runs:

(.) f g = (\x -> f (g x)). 

The problem appears when I try to write it like this

(.) f f = (\x -> f (f x)).   (fof(x) = f(f(x)))

GHCi says:

"Conflicting definitions for `f'
 Bound at: Lab1.hs:27:9
           Lab1.hs:27:12"

Line 27:9 appear on the first time f and line 27:12 appear f again.

Why doesn't Haskell understand (.) f f = (\x -> f (f x))?

解决方案

In Haskell, arguments to a function must have unique names. Using the same name for another argument is not allowed. This is because

foo x y = ...    ===    foo = (\x-> (\y-> ...))

and if y where replaced with x, the second x would just shadow the first inside the ... body: there would be no way to reference the first x from there.

You can just define twice f x = f (f x):

Prelude> :t twice
twice :: (t -> t) -> t -> t
Prelude> twice (+1) 4
6


Alternatively, f (f x) = (.) f f x = join (.) f x:

Prelude Control.Monad> :t join (.)
join (.) :: (b -> b) -> b -> b

join is defined in Control.Monad. For functions, it holds that join g x = g x x. It is also known as W combinator.

E.g. print $ join (.) (+1) 4 prints 6.

这篇关于Haskell - 如何写(。)f f =(\ x - &gt; f(f x))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆