【问题标题】:Implementing Lambda Calculus true and false in Haskell在 Haskell 中实现 Lambda 演算真假
【发布时间】:2017-09-09 16:50:09
【问题描述】:

也许这是一个微不足道的问题,我只是没有正确考虑它。如果是这样,我很抱歉。

我想在 Haskell 中实现 lambda 演算真假函数,然后用它们来实现 if-then-else。这就是我所做的。

true :: t1 -> t2 -> t1
true x y =  x

false :: t1 -> t2 -> t2
false x y = y

-- ifThenElse :: (t2 -> t1 -> t) -> t2 -> t1 -> t
ifThenElse cond thenPart elsePart =  cond thenPart elsePart

注释掉的ifThenElse 类型是GHC 生成的。我担心的是该类型中的t 应该被限制为t1t2。我可以为ifThenElse 写一个类型来完成这个吗?

【问题讨论】:

  • 检查this up
  • 不,因为 Haskell 不知道 cond 应该是 truefalse。对于 Haskell,cond 是一个泛型函数。
  • 你可以写ifThenElse :: (t -> t -> t) -> t -> t -> t
  • 我知道 Haskell 不知道 cond 必须是 truefalse。我在问如何要求它是那个..
  • 开启RankNTypes并要求ifThenElse采用forall t. t -> t -> t类型的条件。

标签: haskell lambda-calculus


【解决方案1】:

你想要这些:

{-# LANGUAGE RankNTypes #-}
-- These are the only two values of this type...
true  :: l -> r -> Either l r
false :: l -> r -> Either l r
true  l _ = Left  l
false _ r = Right r

-- ...and they are the only possible arguments here.
ifThenElse :: (forall l r. l -> r -> Either l r) -> l -> r -> Either l r
ifThenElse = id

如果您想要不同的左右类型,则无法绕过Either

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多