简体   繁体   English

为什么Haskell中的flip和flip(:)功能不同?

[英]Why are flip and flip(:) different functions in Haskell?

Prelude> :t flip
flip :: (a -> b -> c) -> b -> a -> c
Prelude> :t flip(:)
flip(:) :: [a] -> a -> [a]

I don't think (:) is a special syntactic sugar for flip . 我不认为(:)flip的特殊语法糖。 So what has it done to flip ? 那么flip它做了什么?

The "ingredients" are: “成分”是:

flip :: (a -> (b -> c)) -> (b -> (a -> c))
(:) :: d -> ([d] -> [d])

So here flip can take a function (of type a -> b -> c ), and it basically converts it to a function of type b -> a -> c , where thus the "parameters" (technically speaking in Haskell a function has exactly one parameter) are "flipped". 因此,在这里flip可以采用一个函数(类型a -> b -> c ),并且基本上将其转换为类型为b -> a -> c的函数,因此这里的“参数”(从技术上讲在Haskell中是一个函数有且只有一个参数)的“翻转”。

If you write flip (:) , you thus flip the (:) function. 如果您编写flip (:) ,则会翻转(:)函数。 Since the (:) function has type d -> [d] -> [d] , the result is [d] -> d -> [d] . 由于(:)函数的类型为d -> [d] -> [d] ,因此结果为[d] -> d -> [d]

We can however perform a more rigorous type inference. 但是,我们可以执行更严格的类型推断。 Since (:) is the parameter of a function application with flip , we know that the type of (:) should be the same as the type of the parameter of flip , so: 由于(:)是带有flip的函数应用程序的参数,我们知道(:)的类型应与flip参数的类型相同,因此:

   a -> ( b  -> c  )
~  d -> ([d] -> [d])
-----------------------
a ~ d, b ~ [d], c ~ [d]

So we conclude that a ~ d ( a and d are the same type), b ~ c ~ [d] . 因此,我们得出结论a ~ dad是同一类型), b ~ c ~ [d] This thus means that the type of flip (:) is: 因此,这意味着flip (:)的类型为:

flip (:) :: b -> a -> c

or when we perform the replacements to more specific types: 或当我们执行更具体类型的替换时:

flip (:) :: [d] -> d -> [d]

Semantically flip (:) takes a list xs , and an element x , and returns a list where the element is prepended to the given list (so (x:xs) ). 语义上的flip (:)接受一个列表xs和一个元素x ,并返回一个列表,其中该元素位于该列表的前面 (so (x:xs) )。

flip (:) is an application of flip and (:) . flip (:)flip(:)的应用程序。

Their types are 他们的类型是

Prelude> :t flip
flip ::   (a ->  b  ->  c ) -> ( b  -> a ->  c )
Prelude> :t (:)
(:)  ::    a -> [a] -> [a]
Prelude> :t flip (:)
flip (:) ::                     [a] -> a -> [a]

flip just switches the two arguments to a function: flip只是将两个参数切换为一个函数:

flip f y x = f x y

Thus 从而

flip (:) xs x = (:) x xs = x : xs

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

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