Haskell函数可以反转函数调用

Ral*_*lph 7 haskell

我有一个\x f -> f x正在foldM操作中使用的lambda ,其中x是一个值和f :: a -> b.

是否有内置功能可以做到这一点?

我可以更换吗?

foldM (\x f -> f x) ...
Run Code Online (Sandbox Code Playgroud)

和一些 f'

foldM f' ...
Run Code Online (Sandbox Code Playgroud)

我以为flip会这样做,但需要三个参数(flip :: (a -> b -> c) -> b -> a -> c)

它可能类似于|>F#.

Nik*_* B. 20

您可以使用flip idflip ($)(对于函数($)来说只是一个特殊id的):

Prelude> flip id 3 (+2)
5
Prelude> flip ($) 7 (>10)
False
Run Code Online (Sandbox Code Playgroud)

这是一个有趣的使用部分应用:id f xf作为一个功能就是f x.显然,这也是一样的(flip id) x f,flip id你正在寻找的功能也是如此.

如果您喜欢冒险,请尝试推断其类型flip idflip ($)手动.好有趣 :)

  • @Ralph:还有Hackage上的无点包.`cabal install pointfree`和`pointfree"\ ab - > b a"`. (2认同)

Ric*_* T. 8

是的,它被称为flip :: (a -> b -> c) -> b -> a -> c,例如flip (>) 3 5 == True.更多关于hackage的信息和来源:翻转.

你想要的只是反转函数应用程序的参数,对吧?好吧,因为($)是功能应用,通过使用翻转,你可以写flip ($) :: b -> (b -> c) -> c.让我们看看会发生什么 以下是两个前奏函数的来源:

-- from Hackage:
($)                     :: (a -> b) -> a -> b
f $ x                   =  f x

-- from Hackage:
flip                    :: (a -> b -> c) -> b -> a -> c
flip f x y              =  f y x
Run Code Online (Sandbox Code Playgroud)

所以,基本上如果你把类型放在一起,flip ($)就变成了

flip ($) :: 
  b        ->    -- type of x, argument of y and second argument of ($)
  (b -> c) ->    -- type of y, function applied by ($) as its first argument
  c        ->    -- result of the application "y x"
Run Code Online (Sandbox Code Playgroud)

如果您遵循函数的实际定义:

flip ($) = (\f x y -> f y x) ($)    -- from flip's def.
         = \x y -> ($) y x          -- partial application
         = y x                      -- from ($)'s def.
Run Code Online (Sandbox Code Playgroud)