如何使这些动态类型的函数具有类型安全性? [英] How to make these dynamically typed functions type-safe?

查看:63
本文介绍了如何使这些动态类型的函数具有类型安全性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any programming language (or type system) in which you could express the following Python-functions in a statically typed and type-safe way (without having to use casts, runtime-checks etc)?

#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()

推荐答案

1# 这不能用有限类型键入.这意味着几乎没有(如果有的话)编程语言将能够键入该语言.

1# This is not typeable with a finite type. This means that very few (if any) programming languages will be able to type this.

但是,正如您所演示的,x有一种特定的类型,可以键入该函数:

However, as you have demonstrated, there is a specific type for x that allows the function to be typed:

x :: t -> B

其中B是一些具体类型.这导致apply键入为:

Where B is some concrete type. This results in apply being typed as:

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

请注意,Hindley-Milner不会派生此类型.

Note that Hindley-Milner will not derive this type.

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

2# This is easy to represent in Haskell (left as an exercise to the reader...)

这篇关于如何使这些动态类型的函数具有类型安全性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆