【问题标题】:Haskell church numerals can't print | Expected a type, but T has kind `f`Haskell 教堂数字无法打印 |需要一个类型,但 T 有类型 `f`
【发布时间】:2021-07-02 10:57:32
【问题描述】:

我正在关注 Wikipedia 上关于如何处理教会文字的指南。根据文章,有一个 Haskell sn-p:

维基链接Here

type Church a = (a -> a) -> a -> a

church :: Integer -> Church Integer
church 0 = \f -> \x -> x
church n = \f -> \x -> f (church (n-1) f x)

unchurch :: Church Integer -> Integer
unchurch cn = cn (+ 1) 0

但是,当我尝试通过 GHCI 运行它时,出现以下错误:

main.hs:3:15: error:
    * Expecting one more argument to `Church'
      Expected a type, but `Church' has kind `* -> *'
    * In the first argument of `Show', namely `Church'
      In the instance declaration for `Show Church'
  |
3 | instance Show Church where

我尝试在类型上使用deriving show,并且还

instance Show Church Integer where
    show = church

不幸的是,两者都产生了更多错误。我不确定 Church Integer 在函数声明中是什么意思,或者这是否是我无法派生 show 的部分原因?

如何让这个函数打印出来?

【问题讨论】:

  • 试试instance Show (Church Integer) where?
  • 你能添加教程的链接吗?我不确定我是否了解如何为函数构建 Show 实例。
  • @DimaKurilo 好点,编辑了 OT
  • 好吧,本指南中似乎没有 Show 实例。而且您不能为类型定义它(没有语言扩展名)。所以很可能你想展示的不是教堂,而是(unchurch .church)5

标签: haskell lambda-calculus


【解决方案1】:

惯用的方式是将其定义为新类型,a 也应该被普遍量化

>> church 10
10
{-# Language GADTs                    #-}
{-# Language InstanceSigs             #-}
{-# Language RankNTypes               #-}
{-# Language ScopedTypeVariables      #-}
{-# Language StandaloneKindSignatures #-}
{-# Language TypeApplications         #-}

import Data.Kind

type    Church :: Type
newtype Church where
 Church :: (forall a. (a -> a) -> (a -> a)) -> Church

church :: Integer -> Church
church n = Church (ch n) where

 ch :: Integer -> forall a. (a -> a) -> (a -> a)
 ch 0 succ zero = zero
 ch n succ zero = succ (ch (n-1) succ zero)

unchurch :: Church -> Integer
unchurch (Church church) = church @Integer (+ 1) 0

instance Show Church where
 show :: Church -> String
 show = show . unchurch

【讨论】:

  • 我不确定我是否理解正确。运行 church 10 应该返回类似 f(f(f(f(f(f(f(f(f(x))))))))) 的东西,而不仅仅是 10。还是我误解了它?
  • 如果您更改 show 定义,您会得到这样的结果:show (Church church) = church (\x -> "f("++x++")") "x"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2017-06-05
  • 2017-10-23
  • 2017-12-05
  • 1970-01-01
  • 2018-09-17
相关资源
最近更新 更多