[英]Haskell - How to write twice function using (.) f g - function composition
Here is the problem, i need to write the well known twice function 这是问题,我需要编写众所周知的两次函数
(twice= \x-> \x-> x)
but this time using (.)
composition function like (.) fg
. 但是这次使用(.)
等组成函数(.) fg
。
I don't know how to solve it, cause I thought at the beginning to do like: 我不知道该怎么解决,因为我一开始就想这样做:
(.) f g = (\x -> f (g x))
with (g = f)
so it would be like this 与(g = f)
一样
(.) f f = (\x -> f (f x))
but I have a 但我有一个
"Conflicting definitions for `f'" “'f'的定义有冲突”
running on GHCI 在GHCI上运行
So, any suggestions ? 那么,有什么建议吗?
I don't know how you got anything other than a parse input from this: 我不知道除了解析输入之外,您还得到了什么:
(.) f f = (\x -> f (f x))
but the definition you gave: twice = \\x -> \\x -> x
has nothing to do with using something "twice" - indeed if you plug in some values: 但是您给出的定义是: twice = \\x -> \\x -> x
与使用“两次”无关-实际上,如果您插入一些值:
twice a b
= (\x -> \x -> x) a b
= (\x -> (\x -> x)) a b -- (rename the inner x)
= (\x -> (\y -> y)) a b
= ((\x -> (\y -> y)) a) b
= (\y -> y) b
= b
and indeed GHCi will tell you the same: 实际上,GHCi会告诉您相同的内容:
> let twice = \x -> \x -> x
> :t twice
twice :: t -> t1 -> t1
> twice "a" "b"
"b"
Now I guess you want something like this: 现在我想你想要这样的东西:
let twice f x = f (f x)
for example: 例如:
> let twice f x = f (f x)
> twice (+1) 5
7
as you can see twice (+1)
adds 2 (or twice one). 如您所见, twice (+1)
2(或一次两次)。
Now how can you do this using (.)
? 现在如何使用(.)
完成此操作? - Well your intuition was wright: -你的直觉很不错:
> let twice f = f . f
> twice (+1) 5
7
As you asked for a module - this compiles (and loads into GHCi) fine on my system(s): 如您所要求的模块-这可以在我的系统上正常编译(并加载到GHCi中):
module Twice where
twice :: (a->a) -> a -> a
twice f = f . f
this only works if you include (.)
from the prelude (or GHC.Base) - I suspect that you got some kind of excercise that hid the prelude - in this case you have to define (.)
for yourself first (most likely another excercise) 仅当您在前奏(或GHC.Base)中包含(.)
,此方法才起作用-我怀疑您隐藏了前奏的某种锻炼方式-在这种情况下,您必须首先为自己定义(.)
(很可能是另一个锻炼; Tibial)
if you need to implement it yourself: 如果您需要自己实施:
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) g f x = g (f x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.