哪些静态类型语言与Python相似?

2024-04-19 02:04:41 发布

您现在位置:Python中文网/ 问答频道 /正文

Python是我目前所知道的最好的语言,但是由于自动完成,静态类型是一个很大的优势(尽管对动态语言的支持有限,但与静态语言中的支持相比,它是微不足道的)。我很好奇是否有任何语言试图将Python的优点添加到静态类型语言中。特别是,我对具有以下特征的语言很感兴趣:

  • 语法支持:例如字典、数组理解
  • 函数:关键字参数、闭包、元组/多个返回值
  • 运行时修改/创建类
  • 避免在任何地方指定类(在Python中,这是由于duck类型,尽管类型推断在静态类型语言中更有效)
  • 元编程支持:这是在Python中通过反射、注释和元类实现的

是否有任何静态类型的语言具有大量这些特性?


Tags: 函数语言类型参数字典静态语法动态
3条回答

尽管它不是面向对象的,Haskell提供了许多您感兴趣的功能:

  • 对列表理解的语法支持,以及各种排序/绑定构造的do表示法。(字典的语法支持仅限于对列表,例如

    dict = ofElements [("Sputnik", 1957), ("Apollo", 1969), ("Challenger", 1988)]
    
  • 函数支持使用元组类型的完全闭包和多个返回值。关键字参数不受支持,但“隐式参数”的强大功能有时可以替代。

  • 没有类、类型或对象的运行时修改。

  • 通过类型推断避免在任何地方指定类/类型。

  • 使用模板Haskell的元编程。

而且,正是这样你才会有宾至如归的感觉,哈斯克尔有着显著的缩进!

实际上,我认为Haskell总体上与Python有很大的不同,但这主要是因为它具有非常强大的静态类型系统。如果你有兴趣尝试一种静态类型的语言,Haskell是目前最有野心的语言之一。

Cobra是CLR的静态类型语言(作为Boo)。从其网页:

Cobra is a general purpose programming language with:

 - a clean, high-level syntax
 - static and dynamic binding
 - first class support for unit tests and contracts
 - compiled performance with scripting conveniences
 - lambdas and closures
 - extensions and mixins
 - ...and more
Sample code:

"""
This is a doc string for the whole module.
"""


class Person
    """
    This is a class declaration.
    """

    var _name as String  # declare an object variable. every instance of Person will have a name
    var _age as int

    cue init(name as String, age as int)
        _name = name
        _age = age

    def sayHello
        # This is a method

        # In strings, anything in brackets ([]) is evaluated as an expression,
        # converted to a string and substituted into the string:
        print 'Hello. My name is [_name] and I am [_age].'

    def add(i as int, j as int) as int
        """ Adds the two arguments and returns their sum. """
        return i + j

Boo是公共语言基础结构(aka)的静态类型语言。微软.NET平台)。语法是受Python启发的高度,散列/列表/数组是语法的一部分:

i = 5
if i > 5:
    print "i is greater than 5."
else:
    print "i is less than or equal to 5."

hash = {'a': 1, 'b': 2, 'monkey': 3, 42: 'the answer'}
print hash['a']
print hash[42]

for item in hash:
    print item.Key, '=>', item.Value

相关问题 更多 >