9

是否有任何编程语言(或类型系统)可以在其中以静态类型和类型安全的方式表达以下 Python 函数(无需使用强制转换、运行时检查等)?

#1

# My function - What would its type be? 
def Apply(x):
    return x(x)

# Example usage
print Apply(lambda _: 42)

#2

white = None
black = None

def White():
    for x in xrange(1, 10):
        print ("White move #%s" % x)
        yield black

def Black():
    for x in xrange(1, 10):
        print ("Black move #%s" % x)
        yield white

white = White()
black = Black()

# What would the type of the iterator objects be?
for it in white:
    it = it.next()
4

3 回答 3

4

1# 这不是有限类型的类型。这意味着很少(如果有的话)编程语言能够输入这个。

但是,正如您所演示的,x 有一个特定类型,允许键入函数:

x :: t -> B

B具体类型在哪里。这导致apply键入为:

apply :: (t -> B) -> B

请注意,Hindley-Milner 不会派生这种类型。

2# 这在 Haskell 中很容易表示(留给读者作为练习......)

于 2009-07-03T13:07:51.963 回答
2

我使用Rank-N-Types找到了#1的 Haskell 解决方案(仅适用于 GHCi)

{-# LANGUAGE RankNTypes #-}
apply :: (forall a . a -> r) -> r
apply x = x x

apply $ const 42 -- Yields 42
于 2009-11-25T15:13:34.543 回答
0

对于示例 #1,您必须指定 Apply() 的返回类型,然后您传递的所有函数 x 也必须返回 this。如果没有检查,大多数静态类型语言将无法安全地执行此操作,因为您传入的 x 函数可以返回任何内容。

在示例 #2 中,迭代器对象的类型是它们是迭代器。如果您的意思是它们返回的内容,它们会返回迭代器。我不明白为什么这在静态系统中是不可能的,但也许我错过了一些东西。

于 2009-07-03T12:41:53.273 回答