简体   繁体   English

这个函数定义的类型是什么“twice fx = f(fx)”

[英]What is the type of this function definition "twice f x = f (f x)"

This is an excerice question from a book I'm reading now, so what is the type of this definition:这是我现在正在阅读的一本书中的一个练习题,那么这个定义的类型是什么:

twice f x = f (f x)

I understand how the function should work, but I could not figure out the right syntax for it,我了解该函数应该如何工作,但我无法弄清楚它的正确语法,
It takes two arguments, the first is a function and the second is a basic type I think and apply the function twice, one for x and one for the return of (fx) , this is what is was trying to do but obviously it's a wrong syntax它需要两个参数,第一个是函数,第二个是我认为的基本类型,并应用该函数两次,一个用于 x,一个用于 (fx) 的返回,这就是我们正在尝试做的,但显然它是一个错误的语法

twice :: (f -> a) -> a

Can you help me find the type?你能帮我找到类型吗?

You should deducting type of twice starting with it's parameters.您应该从它的参数开始扣除twice类型。

Start with x , it has type x :: _ , but we have no idea what it is, lets call it's type a : x :: a .x开始,它有类型x :: _ ,但我们不知道它是什么,让我们称之为类型a : x :: a

Then we have f , it's a function, from fx we can tell it accepts one argument of type a : f :: a -> _ , let's call new unknown type b : f :: a -> b .然后我们有f ,它是一个函数,从fx我们可以告诉它接受一个类型为a参数: f :: a -> _ ,让我们调用新的未知类型bf :: a -> b

So fx should be of type b : (fx) :: b right?所以fx应该是类型b : (fx) :: b对吗?

But from f (fx) we can tell that (fx) should be a , so we can guess that a and b are actually the same type, so we can drop b and tell that f :: a -> a .但是从f (fx)我们可以看出(fx)应该是a ,所以我们可以猜测ab实际上是相同的类型,所以我们可以去掉b并告诉f :: a -> a

And now we can tell what type twice is: it's a function that takes a -> a function and value of type a and returns result of the first argument function (so a again).现在我们可以知道twice是什么类型:它是一个函数,它接受a -> a函数和类型a值,并返回第一个参数函数的结果(又是a )。

So we have twice :: (a -> a) -> a -> a .所以我们有twice :: (a -> a) -> a -> a

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

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