在 Haskell 中定义替代的 Psi 组合器

问题描述 投票:0回答:1

我一直在用 Haskell 解决一个简单的 Leetcode 问题:正负整数的最大计数

-- First solution
maximumCount :: [Int] -> Int
maximumCount = liftM2 max (length . filter (> 0)) (length . filter (< 0))

-- Custom combinator that's ALMOST the Psi combinator
-- abcde.a(b(ce)(b(de))
myCombinator :: (c -> c -> d) -> (a -> b -> c) -> a -> a -> b -> d
myCombinator f g x y z = f (g x z) (g y z)

-- Second solution
maximumCount' :: [Int] -> Int
maximumCount' = myCombinator max (length .: filter) (> 0) (< 0)

我还没有找到具有这种行为方式的现有组合器。但我确信它可以通过组合现有的组合器来定义。我对组合逻辑还很陌生,所以我可能不知道现有的等价物或派生组合器拼写的方法。

我尝试编写一个函数来组合函数的参数,以便它们对于

on
函数具有正确的形状,但我无法获得正确的定义。

haskell functional-programming combinators combinatory-logic
1个回答
0
投票

它看起来像

on
在阅读器上操作
(->) a
,所以以下应该可以工作。请注意,我首先将二元运算符提升到读取器中并调用
on
:

myCombinator op f = on (liftA2 op) f

然后简化结果:

import Control.Applicative
import Data.Function

myCombinator :: (c -> c -> d) -> (a -> b -> c) -> a -> a -> b -> d
myCombinator = on . liftA2
© www.soinside.com 2019 - 2024. All rights reserved.