静态类型和动态类型语言有什么区别?

发布于 2024-08-06 04:11:50 字数 34 浏览 4 评论 0原文

当我们说一种语言是动态类型与静态类型时,这意味着什么?

What does it mean when we say a language is dynamically typed versus statically typed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

一个人练习一个人 2024-08-13 04:11:51

静态类型:
Java 和 Scala 等语言都是静态类型的。

变量在代码中使用之前必须进行定义和初始化。

例如。整数x; x = 10;

System.out.println(x);

动态打字:
Perl 是一种动态类型语言。

变量在代码中使用之前不需要初始化。

y=10;在代码的后面部分使用这个变量

Static Typing:
The languages such as Java and Scala are static typed.

The variables have to be defined and initialized before they are used in a code.

for ex. int x; x = 10;

System.out.println(x);

Dynamic Typing:
Perl is an dynamic typed language.

Variables need not be initialized before they are used in code.

y=10; use this variable in the later part of code

赴月观长安 2024-08-13 04:11:50

静态类型语言

如果变量的类型在编译时已知,则该语言是静态类型的。对于某些语言,这意味着您作为程序员必须指定每个变量的类型;其他语言(例如:Java、C、C++)提供某种形式的类型推断,即类型系统推断变量类型的能力(例如:OCaml、Haskell、Scala、Kotlin)。

这里的主要优点是编译器可以完成各种检查,因此可以在很早的阶段捕获很多微不足道的错误。

示例:C、C++、Java、Rust、Go、Scala

动态类型语言

如果类型与运行时值关联,而不是命名变量/字段/等,则该语言是动态类型的。这意味着您作为程序员可以编写得更快一些,因为您不必每次都指定类型(除非使用具有类型推断功能的静态类型语言)。

示例:Perl、Ruby、Python、PHP、JavaScript、Erlang

大多数脚本语言都具有此功能,因为无论如何都没有编译器进行静态类型检查,但您可能会发现自己正在寻找由于解释器错误解释类型而导致的错误的一个变量。幸运的是,脚本往往很小,因此错误没有太多隐藏的地方。

大多数动态类型语言确实允许您提供类型信息,但并不需要它。目前正在开发的一种语言 Rascal 采用混合方法,允许在函数内进行动态类型输入,但强制执行静态类型输入函数签名。

Statically typed languages

A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is; other languages (e.g.: Java, C, C++) offer some form of type inference, the capability of the type system to deduce the type of a variable (e.g.: OCaml, Haskell, Scala, Kotlin).

The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage.

Examples: C, C++, Java, Rust, Go, Scala

Dynamically typed languages

A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with type inference).

Examples: Perl, Ruby, Python, PHP, JavaScript, Erlang

Most scripting languages have this feature as there is no compiler to do static type-checking anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide.

Most dynamically typed languages do allow you to provide type information, but do not require it. One language that is currently being developed, Rascal, takes a hybrid approach allowing dynamic typing within functions but enforcing static typing for the function signature.

做个少女永远怀春 2024-08-13 04:11:50

类型检查是验证和强制执行类型约束的过程。

  • 静态类型编程语言在编译时进行类型检查。
    示例:Java、C、C++。

  • 动态类型编程语言在运行时进行类型检查。
    示例:
    Perl、Ruby、Python、PHP、JavaScript。

Type checking is the process of verifying and enforcing the constraints of types.

  • Statically typed programming languages do type checking at compile-time.
    Examples: Java, C, C++.

  • Dynamically typed programming languages do type checking at run-time.
    Examples:
    Perl, Ruby, Python, PHP, JavaScript.

最舍不得你 2024-08-13 04:11:50

下面是一个对比 Python(动态类型)和 Go(静态类型)如何处理类型错误的示例:

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

Python 在运行时进行类型检查,因此:

silly(2)

运行得很好,并产生预期的输出 Hi 。仅当遇到有问题的行时才会引发错误

silly(-1)

类型错误:+ 不支持的操作数类型:“int”和“str”

因为相关行实际上被执行了。

另一方面,Go 在编译时进行类型检查:

package main

import ("fmt"
)

func silly(a int) {
    if (a > 0) {
        fmt.Println("Hi")
    } else {
        fmt.Println("3" + 5)
    }
}

func main() {
    silly(2)
}

上面的代码将无法编译,并出现以下错误:

无效操作:“3”+ 5(字符串和整数类型不匹配)

Here is an example contrasting how Python (dynamically typed) and Go (statically typed) handle a type error:

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

Python does type checking at run time, and therefore:

silly(2)

Runs perfectly fine, and produces the expected output Hi. Error is only raised if the problematic line is hit:

silly(-1)

Produces

TypeError: unsupported operand type(s) for +: 'int' and 'str'

because the relevant line was actually executed.

Go on the other hand does type-checking at compile time:

package main

import ("fmt"
)

func silly(a int) {
    if (a > 0) {
        fmt.Println("Hi")
    } else {
        fmt.Println("3" + 5)
    }
}

func main() {
    silly(2)
}

The above will not compile, with the following error:

invalid operation: "3" + 5 (mismatched types string and int)
几味少女 2024-08-13 04:11:50

简单地说:在静态类型语言中,变量的类型是静态,这意味着一旦将变量设置为类型,就无法更改它。这是因为类型与变量相关联,而不是与它引用的值相关联。

例如在 Java 中:

String str = "Hello";  // variable str statically typed as string
str = 5;               // would throw an error since str is
                       // supposed to be a string only

另一方面:在动态类型语言中,变量的类型是动态,这意味着在将变量设置为类型后,您可以更改它。这是因为类型与它所假定的值相关联,而不是与变量本身相关联。

例如在 Python 中:

some_str = "Hello"  # variable some_str is linked to a string value
some_str = 5        # now it is linked to an integer value; perfectly OK

因此,最好将动态类型语言中的变量视为只是指向类型值的通用指针

总而言之,类型描述(或应该描述)语言中的变量而不是语言本身。恕我直言,与具有动态类型变量的语言相比,它可以更好地用作具有静态类型变量的语言

静态类型语言通常是编译语言,因此编译器会检查类型(这很有意义吗?因为类型不允许在运行时更改)。

动态类型语言通常是解释性的,因此类型检查(如果有)在使用它们时在运行时发生。这当然会带来一些性能成本,也是动态语言(例如 python、ruby、php)扩展性不如类型化语言(java、c# 等)的原因之一。从另一个角度来看,静态类型语言有更多的启动成本:让你通常编写更多的代码,更难的代码。但这会在以后得到回报。

好消息是双方都在借鉴对方的特色。类型化语言正在合并更多的动态功能,例如,c# 中的泛型和动态库,而动态语言则包括更多的类型检查,例如 python 中的类型注释,或 PHP 的 HACK 变体,这些通常不是该语言的核心,可以在要求。

在技​​术选择方面,双方并不存在本质上的优势。您是否想要更多的控制权或灵活性只是一个偏好问题。只需为工作选择正确的工具,并确保在考虑转换之前检查相反的可用工具。

Simply put it this way: in a statically typed language variables' types are static, meaning once you set a variable to a type, you cannot change it. That is because typing is associated with the variable rather than the value it refers to.

For example in Java:

String str = "Hello";  // variable str statically typed as string
str = 5;               // would throw an error since str is
                       // supposed to be a string only

Where on the other hand: in a dynamically typed language variables' types are dynamic, meaning after you set a variable to a type, you CAN change it. That is because typing is associated with the value it assumes rather than the variable itself.

For example in Python:

some_str = "Hello"  # variable some_str is linked to a string value
some_str = 5        # now it is linked to an integer value; perfectly OK

So, it is best to think of variables in dynamically typed languages as just generic pointers to typed values.

To sum up, type describes (or should have described) the variables in the language rather than the language itself. It could have been better used as a language with statically typed variables versus a language with dynamically typed variables IMHO.

Statically typed languages are generally compiled languages, thus, the compilers check the types (make perfect sense right? as types are not allowed to be changed later on at run time).

Dynamically typed languages are generally interpreted, thus type checking (if any) happens at run time when they are used. This of course brings some performance cost, and is one of the reasons dynamic languages (e.g., python, ruby, php) do not scale as good as the typed ones (java, c#, etc.). From another perspective, statically typed languages have more of a start-up cost: makes you usually write more code, harder code. But that pays later off.

The good thing is both sides are borrowing features from the other side. Typed languages are incorporating more dynamic features, e.g., generics and dynamic libraries in c#, and dynamic languages are including more type checking, e.g., type annotations in python, or HACK variant of PHP, which are usually not core to the language and usable on demand.

When it comes to technology selection, neither side has an intrinsic superiority over the other. It is just a matter of preference whether you want more control to begin with or flexibility. just pick the right tool for the job, and make sure to check what is available in terms of the opposite before considering a switch.

铁轨上的流浪者 2024-08-13 04:11:50

http://en.wikipedia.org/wiki/Type_system

静态类型

据说有一种编程语言使用
类型检查时的静态类型
在编译时执行为
与运行时相反。在静态类型中,
类型与变量相关联
不是价值观。静态类型语言
包括 Ada、C、C++、C#、JADE、Java、
Fortran、Haskell、ML、Pascal、Perl
(关于区分
标量、数组、散列和
子例程)和 Scala。静态类型
是程序的有限形式
验证(参见类型安全):
因此,它允许多种类型
尽早发现错误
开发周期。静态型
检查器仅评估类型
可以确定的信息
编译时间,但能够验证
所检查的条件成立
所有可能的执行
程序,这消除了需要
每次重复类型检查
程序被执行。程序执行
也可以变得更有效率(即
更快或占用更少的内存)
省略运行时类型检查和
启用其他优化。

因为它们评估类型信息
在编译期间,因此缺乏
仅键入信息
运行时可用,静态类型
跳棋是保守的。他们会
拒绝一些可能的程序
在运行时表现良好,但是
不能静态地确定
类型良好。例如,即使
表达总是
在运行时评估为 true,a
包含代码的程序

if <复杂测试>然后 42 else <类型错误>

将因类型错误而被拒绝,因为
静态分析无法确定
else 分支不会
已采取。[1]保守行为
静态类型检查器的数量是
有利时
很少评估为 false:A
静态类型检查器可以检测类型
很少使用的代码路径中的错误。
没有静态类型检查,即使
100% 代码的代码覆盖率测试
覆盖范围可能无法找到此类
类型错误。代码覆盖率测试可能
无法检测到此类类型错误
因为所有地方的结合
价值创造的地方
使用特定值的地方
必须考虑在内。

使用最广泛的静态类型
语言在形式上不是类型安全的。
他们的做法有“漏洞”
编程语言规范
使程序员能够编写代码
从而规避验证
由静态类型检查器执行并且
从而解决更广泛的问题。
例如,Java 和大多数 C 风格
语言具有类型双关语,并且
Haskell 具有以下功能:
unsafePerformIO:此类操作可能
在运行时不安全,因为它们可以
由于以下原因导致不良行为
错误地输入值时
程序运行。

动态输入

据说一种编程语言是
动态类型,或者只是“动态”,
当其大部分类型检查
是在运行时执行的,而不是
在编译时。在动态类型中,
类型与值不相关
变量。动态类型语言
包括 Groovy、JavaScript、Lisp、Lua、
Objective-C、Perl(相对于
用户定义类型但不是内置类型
类型)、PHP、Prolog、Python、Ruby、
Smalltalk 和 Tcl。与静态相比
打字,动态打字可以更多
灵活(例如允许程序
基于生成类型和功能
关于运行时数据),尽管在
以较少的先验保证为代价。
这是因为动态类型
语言接受并尝试
执行一些程序可能是
被静态类型判定为无效
检查器。

动态类型可能会导致运行时
类型错误——也就是说,在运行时,
值可能具有意外的类型,并且
对于该类型来说无意义的操作
被应用。该操作可能会发生
很久之后的地方
犯了编程错误——也就是说,
数据类型错误的地方
传递到不应该的地方
有。这使得该错误很难
定位。

动态类型语言系统,
与静态类型相比
表兄弟,减少“编译时”
检查源代码(但会
例如,检查程序
语法上是正确的)。运行时
检查可能会更多
复杂,因为他们可以使用
动态信息以及任何
期间出现的信息
汇编。另一方面,
运行时检查仅断言
条件在特定条件下成立
程序的执行,以及这些
对每个重复检查
程序的执行。

动态类型开发
语言通常支持
编程实践,例如单元
测试。测试是一个关键实践
专业软件开发,以及
尤为重要的是
动态类型语言。在
实践,进行测试以确保
正确的程序运行可以检测到
误差范围比静态误差范围大得多
类型检查,但反过来不能
尽可能全面地搜索
测试和静态错误
类型检查都能够检测到。
测试可以纳入
软件构建周期,在这种情况下
可以被认为是“编译时”
检查,因为程序用户将
不必手动运行此类测试。

参考文献

  1. 本杰明·皮尔斯 (2002)。类型和编程语言。麻省理工学院出版社。
    ISBN 0-262-16209-1。

http://en.wikipedia.org/wiki/Type_system

Static typing

A programming language is said to use
static typing when type checking is
performed during compile-time as
opposed to run-time. In static typing,
types are associated with variables
not values. Statically typed languages
include Ada, C, C++, C#, JADE, Java,
Fortran, Haskell, ML, Pascal, Perl
(with respect to distinguishing
scalars, arrays, hashes and
subroutines) and Scala. Static typing
is a limited form of program
verification (see type safety):
accordingly, it allows many type
errors to be caught early in the
development cycle. Static type
checkers evaluate only the type
information that can be determined at
compile time, but are able to verify
that the checked conditions hold for
all possible executions of the
program, which eliminates the need to
repeat type checks every time the
program is executed. Program execution
may also be made more efficient (i.e.
faster or taking reduced memory) by
omitting runtime type checks and
enabling other optimizations.

Because they evaluate type information
during compilation, and therefore lack
type information that is only
available at run-time, static type
checkers are conservative. They will
reject some programs that may be
well-behaved at run-time, but that
cannot be statically determined to be
well-typed. For example, even if an
expression always
evaluates to true at run-time, a
program containing the code

if <complex test> then 42 else <type error>

will be rejected as ill-typed, because
a static analysis cannot determine
that the else branch won't be
taken.[1] The conservative behaviour
of static type checkers is
advantageous when
evaluates to false infrequently: A
static type checker can detect type
errors in rarely used code paths.
Without static type checking, even
code coverage tests with 100% code
coverage may be unable to find such
type errors. Code coverage tests may
fail to detect such type errors
because the combination of all places
where values are created and all
places where a certain value is used
must be taken into account.

The most widely used statically typed
languages are not formally type safe.
They have "loopholes" in the
programming language specification
enabling programmers to write code
that circumvents the verification
performed by a static type checker and
so address a wider range of problems.
For example, Java and most C-style
languages have type punning, and
Haskell has such features as
unsafePerformIO: such operations may
be unsafe at runtime, in that they can
cause unwanted behaviour due to
incorrect typing of values when the
program runs.

Dynamic typing

A programming language is said to be
dynamically typed, or just 'dynamic',
when the majority of its type checking
is performed at run-time as opposed to
at compile-time. In dynamic typing,
types are associated with values not
variables. Dynamically typed languages
include Groovy, JavaScript, Lisp, Lua,
Objective-C, Perl (with respect to
user-defined types but not built-in
types), PHP, Prolog, Python, Ruby,
Smalltalk and Tcl. Compared to static
typing, dynamic typing can be more
flexible (e.g. by allowing programs to
generate types and functionality based
on run-time data), though at the
expense of fewer a priori guarantees.
This is because a dynamically typed
language accepts and attempts to
execute some programs which may be
ruled as invalid by a static type
checker.

Dynamic typing may result in runtime
type errors—that is, at runtime, a
value may have an unexpected type, and
an operation nonsensical for that type
is applied. This operation may occur
long after the place where the
programming mistake was made—that is,
the place where the wrong type of data
passed into a place it should not
have. This makes the bug difficult to
locate.

Dynamically typed language systems,
compared to their statically typed
cousins, make fewer "compile-time"
checks on the source code (but will
check, for example, that the program
is syntactically correct). Run-time
checks can potentially be more
sophisticated, since they can use
dynamic information as well as any
information that was present during
compilation. On the other hand,
runtime checks only assert that
conditions hold in a particular
execution of the program, and these
checks are repeated for every
execution of the program.

Development in dynamically typed
languages is often supported by
programming practices such as unit
testing. Testing is a key practice in
professional software development, and
is particularly important in
dynamically typed languages. In
practice, the testing done to ensure
correct program operation can detect a
much wider range of errors than static
type-checking, but conversely cannot
search as comprehensively for the
errors that both testing and static
type checking are able to detect.
Testing can be incorporated into the
software build cycle, in which case it
can be thought of as a "compile-time"
check, in that the program user will
not have to manually run such tests.

References

  1. Pierce, Benjamin (2002). Types and Programming Languages. MIT Press.
    ISBN 0-262-16209-1.
并安 2024-08-13 04:11:50

编译与解释

“当源代码被翻译时”

  • 源代码:原始代码(通常由人类输入到计算机中)
  • 翻译:将源代码转换为计算机可以处理的内容读取(即机器代码)
  • 运行时:程序执行命令的时期(编译后,如果已编译)
  • 编译语言:运行时之前翻译的代码
  • 解释语言:在执行期间动态翻译的代码

键入

“当检查类型时”

5 + '3' 是强类型中类型错误的示例Go 和 Python 等语言,因为它们不允许“类型强制” ->值在某些上下文中更改类型的能力,例如合并两种类型。 弱类型语言(例如 JavaScript)不会引发类型错误(结果为 '53')。

  • 静态:在运行时之前检查的类型
  • 动态:在执行期间动态检查的类型

“静态和编译”和“动态和解释”的定义相当类似...但请记住它是“检查类型时”与“翻译源代码时”。

无论语言是编译的还是解释的,您都会得到相同类型的错误!您需要在概念上区分这些术语。


Python 示例

动态、解释

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

silly(2)

因为 Python 既是解释型又是动态类型的,所以它只对正在执行的代码进行转换和类型检查。 else 块永远不会执行,因此 5 + '3' 根本不会被查看!

如果它是静态类型的怎么办?

在代码运行之前就会抛出类型错误。即使它被解释,它仍然在运行时之前执行类型检查。

如果它被编译了怎么办?

else 块将在运行时之前被翻译/查看,但因为它是动态类型的,所以不会抛出错误!动态类型语言在执行之前不会检查类型,并且该行永远不会执行。


Go 示例

静态、编译

package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}

在运行之前检查类型(静态),并立即捕获类型错误!如果被解释,类型仍然会在运行时之前被检查,具有相同的结果。如果它是动态的,即使在编译期间查看代码,它也不会抛出任何错误。


性能

如果编译语言是静态类型的(相对于动态类型的),那么它在运行时会有更好的性能;了解类型可以优化机器代码。

静态类型语言本质上在运行时具有更好的性能,因为不需要在执行时动态检查类型(它在运行之前检查)。

同样,编译语言在运行时速度更快,因为代码已经被翻译,而不需要即时“解释”/翻译它。

请注意,编译语言和静态类型语言在分别运行翻译和类型检查之前都会有延迟。


更多差异

静态类型会尽早捕获错误,而不是在执行期间发现错误(对于长程序特别有用)。它更加“严格”,因为它不允许程序中任何地方出现类型错误,并且通常会阻止变量更改类型,这进一步防止了意外错误。

num = 2
num = '3' // ERROR

动态类型更加灵活,一些人对此表示赞赏。它通常允许变量更改类型,这可能会导致意外错误。

Compiled vs. Interpreted

"When source code is translated"

  • Source Code: Original code (usually typed by a human into a computer)
  • Translation: Converting source code into something a computer can read (i.e. machine code)
  • Run-Time: Period when program is executing commands (after compilation, if compiled)
  • Compiled Language: Code translated before run-time
  • Interpreted Language: Code translated on the fly, during execution

Typing

"When types are checked"

5 + '3' is an example of a type error in strongly typed languages such as Go and Python, because they don't allow for "type coercion" -> the ability for a value to change type in certain contexts such as merging two types. Weakly typed languages, such as JavaScript, won't throw a type error (results in '53').

  • Static: Types checked before run-time
  • Dynamic: Types checked on the fly, during execution

The definitions of "Static & Compiled" and "Dynamic & Interpreted" are quite similar...but remember it's "when types are checked" vs. "when source code is translated".

You'll get the same type errors irrespective of whether the language is compiled or interpreted! You need to separate these terms conceptually.


Python Example

Dynamic, Interpreted

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

silly(2)

Because Python is both interpreted and dynamically typed, it only translates and type-checks code it's executing on. The else block never executes, so 5 + '3' is never even looked at!

What if it was statically typed?

A type error would be thrown before the code is even run. It still performs type-checking before run-time even though it is interpreted.

What if it was compiled?

The else block would be translated/looked at before run-time, but because it's dynamically typed it wouldn't throw an error! Dynamically typed languages don't check types until execution, and that line never executes.


Go Example

Static, Compiled

package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}

The types are checked before running (static) and the type error is immediately caught! The types would still be checked before run-time if it was interpreted, having the same result. If it was dynamic, it wouldn't throw any errors even though the code would be looked at during compilation.


Performance

A compiled language will have better performance at run-time if it's statically typed (vs. dynamically); knowledge of types allows for machine code optimization.

Statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running).

Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to "interpret"/translate it on the fly.

Note that both compiled and statically typed languages will have a delay before running for translation and type-checking, respectively.


More Differences

Static typing catches errors early, instead of finding them during execution (especially useful for long programs). It's more "strict" in that it won't allow for type errors anywhere in your program and often prevents variables from changing types, which further defends against unintended errors.

num = 2
num = '3' // ERROR

Dynamic typing is more flexible, which some appreciate. It typically allows for variables to change types, which can result in unexpected errors.

也只是曾经 2024-08-13 04:11:50

不幸的是,术语“动态类型”具有误导性。所有语言都是静态类型的,类型是表达式的属性(而不是某些人认为的值的属性)。然而,有些语言只有一种类型。这些被称为单一类型语言。这种语言的一个例子是无类型 lambda 演算。

在无类型 lambda 演算中,所有项都是 lambda 项,并且可以对一项执行的唯一操作是将其应用于另一项。因此,所有操作总是导致无限递归或 lambda 项,但永远不会发出错误信号。

然而,如果我们用原始数字和算术运算来增强无类型 lambda 演算,那么我们可能会执行无意义的运算,例如将两个 lambda 项加在一起:(λx.x) + (λy.y)。有人可能会说,唯一明智的做法是在发生这种情况时发出错误信号,但为了能够做到这一点,每个值都必须用一个指示符来标记,以指示该项是 lambda 项还是数字。然后,加法运算符将检查两个参数是否确实被标记为数字,如果不是,则发出错误信号。请注意,这些标记不是类型,因为类型是程序的属性,而不是这些程序生成的值的属性。

执行此操作的单一类型语言称为动态类型。

JavaScript、Python 和 Ruby 等语言都是单一类型的。同样,JavaScript 中的 typeof 运算符和 Python 中的 type 函数的名称具有误导性;它们返回与操作数相关的标签,而不是其类型。同样,C++ 中的 dynamic_cast 和 Java 中的 instanceof 不进行类型检查。

The terminology "dynamically typed" is unfortunately misleading. All languages are statically typed, and types are properties of expressions (not of values as some think). However, some languages have only one type. These are called uni-typed languages. One example of such a language is the untyped lambda calculus.

In the untyped lambda calculus, all terms are lambda terms, and the only operation that can be performed on a term is applying it to another term. Hence all operations always result in either infinite recursion or a lambda term, but never signal an error.

However, were we to augment the untyped lambda calculus with primitive numbers and arithmetic operations, then we could perform nonsensical operations, such adding two lambda terms together: (λx.x) + (λy.y). One could argue that the only sane thing to do is to signal an error when this happens, but to be able to do this, each value has to be tagged with an indicator that indicates whether the term is a lambda term or a number. The addition operator will then check that indeed both arguments are tagged as numbers, and if they aren't, signal an error. Note that these tags are not types, because types are properties of programs, not of values produced by those programs.

A uni-typed language that does this is called dynamically typed.

Languages such as JavaScript, Python, and Ruby are all uni-typed. Again, the typeof operator in JavaScript and the type function in Python have misleading names; they return the tags associated with the operands, not their types. Similarly, dynamic_cast in C++ and instanceof in Java do not do type checks.

遇到 2024-08-13 04:11:50

在编程中,数据类型是一种分类,它告诉我们 1) 变量将保存什么类型的值,以及 2) 可以对这些值执行哪些数学、关系和逻辑运算而不会出错。

当人们在以下上下文中提到“类型”时,他们的意思是“数据类型”。

在每种编程语言中,为了最大限度地减少出现错误的机会,类型检查是在程序执行之前或期间进行的。根据类型检查的时机,有两种类型的编程语言:静态类型动态类型语言(或混合,其中用户说明每个变量使用哪个(静态/动态))。

此外,根据隐式类型转换是否发生,有两种类型的编程语言:强类型弱类型语言。

有两个轴在中间交叉的图表,每个象限有两种编程语言的名称。底部的图例如下: “打字:静态与动态,强与弱” 水平轴在左侧标记为“动态”,在垂直轴上标记为“强”,在底部标记为“弱”。静态强象限,其中 C# 强于 Java,Python 和 Ruby 位于动态强象限,Python 强于 Ruby,JavaScript 和 PHP 位于动态弱象限,PHP 弱于 JavaScript C 和 C++。位于静态弱象限,C++ 比 C 弱。

静态类型:

  • 类型检查在编译时完成

  • 在源代码中,在变量声明时(将值分配给新变量时),该变量的数据类型必须显式指定(即不能隐式/推断/猜测),因为如果在源代码中指定数据类型,则在编译时源代码将转换为机器代码并允许进行类型检查

  • 这里,数据类型与变量相关联(变量名,而不是值),例如,int count。该关联是静态的(固定的)

  • 如果我们尝试通过分配不同数据类型的值(int count = “Hello”),然后我们会得到一个错误

  • 如果我们尝试通过使用不同的数据类型(boolean count)重新声明已经声明的变量(int count)来更改数据类型)那么我们也会得到一个错误

int count;         /* count is int type, association between data type
                      and variable is static or fixed */

count = 10;        // no error 
count = 'Hello';   // error 
boolean count;     // error 
  • 由于类型检查和类型错误检测是在编译时完成的,因此在运行时不需要进一步的类型检查。因此,程序变得更加优化,执行速度更快

  • 如果我们想要更多类型严格的代码,那么选择这种类型的语言是更好的选择

  • 示例:Java、C、C++、Go、Swift 等

动态类型:

  • 类型检查在运行时完成

  • 在源代码中,在变量声明时,不需要显式指定该变量的数据类型。因为类型检查是在运行时完成的,所以语言的系统根据变量分配值的数据类型来确定变量类型

  • 此处,数据类型与分配给变量的值相关联。例如,var foo = 10:10 是一个数字,所以现在 foo 是数字数据类型。但这种关联是动态的(灵活的)

  • 我们可以通过分配不同数据类型的值(foo = "Hi") 进入其中,不会产生错误

  • 我们可以轻松地更改已经声明的变量 (var foo = 10) 的数据类型,方法是使用其他数据类型的值 (var foo = true),不产生错误

var foo;            // without assigned value, variable holds undefined data type 

var foo = 10;       // foo is Number type now, association between data 
                    // type and value is dynamic / flexible 
foo = 'Hi';         // foo is String type now, no error 
var foo = true;     // foo is Boolean type now, no error 
  • 由于类型检查和类型错误检测是在运行时完成的,动态类型程序的优化程度较低,导致执行速度较慢。尽管这些类型的语言如果实现 JIT(即时)编译器,执行速度会更快

  • 如果我们想轻松地编写和执行代码,那么这种类型的语言是更好的选择,但在这里我们仍然不幸地得到运行时错误

  • 示例:Python、JavaScript、PHP、Ruby 等

In programming, Data Type is a Classification which tells us 1) what type of value a variable will hold and 2) which mathematical, relational and logical operations can be done on those values without getting an error.

When people mention "type" in the following contexts, they mean "data types".

In each programming language, to minimize the chance of getting an error, type checking is done either before or during program execution. Depending on the Timing of Type Checking, there are two types of programming languages: Statically Typed and Dynamically Typed languages (or mixed, where the user says which to use (static/dynamic) for each variable).

Also, depending on whether Implicit Type Conversion happens or not, there are two types of programming languages: Strongly Typed and Weakly Typed languages.

Graph with two axes that cross in the middle, with the names of two programming languages in each quadrant. The legend at the bottom reads: "Typing: Static vs. Dynamic, Strong vs. Weak". The horizontal axis is labelled DYNAMIC on the left and STATIC on the right. The vertical axis is labelled STRONG at the top and WEAK at the bottom. C# and Java are in the Static-Strong quadrant, with C# stronger than Java. Python and Ruby are in the Dynamic-Strong quadrant, with Python stronger than Ruby. JavaScript and PHP are in the Dynamic-Weak quadrant, with PHP weaker than JavaScript. C and C++ are in the Static-Weak quadrant, with C++ weaker than C.

Statically Typed :

  • Type checking is done at compile time

  • In source code, at the time of variable declaration (the time when a value is assigned to a new variable), the data type of that variable must be explicitly specified (i.e., cannot be implicit/inferred/guessed) because, if the data type is specified in source code, then at compile time that source code will be converted to machine code and allow type checking to happen

  • Here, data type is associated with the variable (the variable name, not the value) like, int count. This association is static (fixed)

  • If we try to change the data type of an already declared variable (int count) by assigning a value of a different data type (int count = "Hello") into it, then we will get an error

  • If we try to change the data type by redeclaring an already declared variable (int count) using a different data type (boolean count) then we will also get an error

int count;         /* count is int type, association between data type
                      and variable is static or fixed */

count = 10;        // no error 
count = 'Hello';   // error 
boolean count;     // error 
  • As type checking and type error detection are done at compile time, no further type checking is needed during runtime. Thus, the program becomes more optimized, resulting in faster execution

  • If we want more type-rigid code, then choosing this type of language is better option

  • Examples: Java, C, C++, Go, Swift, etc.

Dynamically Typed :

  • Type checking is done at runtime

  • In source code, at the time of variable declaration, there is no need to explicitly specify the data type of that variable. Because type checking is done during runtime, the language's system determines variable type from the data type of the assigned value of that variable

  • Here, data type is associated with the value assigned to the variable. For example, var foo = 10: 10 is a Number so now foo is of Number data type. But this association is dynamic (flexible)

  • we can easily change data type of an already declared variable (var foo = 10), by assigning a value of a different data type (foo = "Hi") into it, not producing an error

  • we can easily change data type of an already declared variable (var foo = 10), by redeclaring it using value of other data type (var foo = true), not producing an error

var foo;            // without assigned value, variable holds undefined data type 

var foo = 10;       // foo is Number type now, association between data 
                    // type and value is dynamic / flexible 
foo = 'Hi';         // foo is String type now, no error 
var foo = true;     // foo is Boolean type now, no error 
  • As type checking and type error detection is done at runtime, a dynamically typed program is less optimized, results in slower execution. Although execution of these type of languages can be faster if they implement JIT (Just In Time) Compiler

  • If we want to write and execute code easily, then this type of language is the better option, but here we can still unfortunately get a runtime error

  • Examples : Python, JavaScript, PHP, Ruby etc.

笛声青案梦长安 2024-08-13 04:11:50

静态类型语言:每个变量和表达式在编译时都是已知的。

int a; a 在运行时只能取整数类型值)

示例:C、C++、Java

动态类型语言:变量在运行时可以接收不同的值,其类型为在运行时定义。

var a; a 可以在运行时采用任何类型的值)

示例:Ruby、Python。

Statically typed languages: each variable and expression is already known at compile time.

(int a; a can take only integer type values at runtime)

Examples: C, C++, Java

Dynamically typed languages: variables can receive different values at runtime and their type is defined at run time.

(var a; a can take any kind of values at runtime)

Examples: Ruby, Python.

温暖的光 2024-08-13 04:11:50

静态类型语言在编译时进行类型检查,并且类型不能更改。 (不要对类型转换注释表现得可爱,会创建一个新的变量/引用)。

动态类型语言在运行时进行类型检查,并且变量的类型可以在运行时更改。

Statically typed languages type-check at compile time and the type can NOT change. (Don't get cute with type-casting comments, a new variable/reference is created).

Dynamically typed languages type-check at run-time and the type of an variable CAN be changed at run-time.

牵强ㄟ 2024-08-13 04:11:50

甜蜜而简单的定义,但符合需要:
静态类型语言将类型绑定到变量的整个作用域(Seg:SCALA)
动态类型语言将类型绑定到变量引用的实际值。

Sweet and simple definitions, but fitting the need:
Statically typed languages binds the type to a variable for its entire scope (Seg: SCALA)
Dynamically typed languages bind the type to the actual value referenced by a variable.

朦胧时间 2024-08-13 04:11:50

静态类型: 在编译时执行类型检查

静态类型语言的实际含义是:

  • 必须指定变量的类型
  • 变量只能引用特定类型的对象*
  • 将在编译时执行值的类型检查,并且届时将报告任何类型检查
  • 的大小变量在编译时计算

静态类型语言的示例有 C、C++、Java。

动态类型: 在运行时执行类型检查

动态类型语言的实际含义是:

  • 无需指定变量的类型,
  • 同一变量可以引用不同类型的对象

Python、Ruby 都是动态类型语言的例子。

请注意,无论静态或动态类型,变量的内存分配都是在执行应用程序/程序(加载到内存中)时执行的


* 某些对象可以通过类型转换将其分配给不同类型的变量(这是在C 和 C++ 等语言)

Static Type: Type checking performed at compile time.

What actually mean by static type language:

  • type of a variable must be specified
  • a variable can reference only a particular type of object*
  • type check for the value will be performed at the compile time and any type checking will be reported at that time
  • size of a variable is computed at compile time

Example of static type language are C, C++, Java.

Dynamic Type: Type checking performed at runtime.

What actually mean by dynamic type language:

  • no need to specify type of the variable
  • same variable can reference to different type of objects

Python, Ruby are examples of dynamic type language.

Note that regardless of static or dynamic type, memory allocation for variables is performed when an app/program executed (loaded into the memory)


* Some objects can be assigned to different type of variables by typecasting it (a very common practice in languages like C and C++)

独留℉清风醉 2024-08-13 04:11:50
  • 在静态类型语言中,变量与编译时已知的类型相关联,并且该类型在程序执行过程中保持不变。同样,变量只能被分配一个已知/指定类型的实例值。
  • 在动态类型语言中,变量没有类型,并且其在执行期间的值可以是任何形状和形式的任何值。
  • In a statically typed language, a variable is associated with a type which is known at compile time, and that type remains unchanged throughout the execution of a program. Equivalently, the variable can only be assigned a value which is an instance of the known/specified type.
  • In a dynamically typed language, a variable has no type, and its value during execution can be anything of any shape and form.
酒几许 2024-08-13 04:11:50

静态类型语言(编译器解析方法调用和编译引用):

  • 通常性能更好
  • ,编译速度更快,错误反馈
  • 更好,IDE 支持
  • 不适合处理未定义的数据格式,
  • 在未定义模型时更难开始开发,
  • 更长的编译时间
  • 在许多情况下需要 编写更多代码

动态类型语言(在运行程序中做出的决定):

  • 性能较低
  • 开发速度更快
  • 有些错误可能只有在运行时稍后才能检测到
  • ,适合未定义的数据格式(元编程)

Static typed languages (compiler resolves method calls and compile references):

  • usually better performance
  • faster compile error feedback
  • better IDE support
  • not suited for working with undefined data formats
  • harder to start a development when model is not defined when
  • longer compilation time
  • in many cases requires to write more code

Dynamic typed languages (decisions taken in running program):

  • lower performance
  • faster development
  • some bugs might be detected only later in run-time
  • good for undefined data formats (meta programming)
把时间冻结 2024-08-13 04:11:50

静态类型语言(如 C++、Java)和动态类型语言(如 Python)仅在变量类型的执行方面有所不同。
静态类型语言具有变量的静态数据类型,这里在编译期间检查数据类型,因此调试要简单得多......而动态类型语言则不这样做同样,执行程序时会检查数据类型,因此调试有点困难。

而且它们之间的差异非常小,并且可以与强类型弱类型语言相关。强类型语言不允许您将一种类型用作另一种类型,例如。 C 和 C++ ...而弱类型语言允许例如.python

Statically typed languages like C++, Java and Dynamically typed languages like Python differ only in terms of the execution of the type of the variable.
Statically typed languages have static data type for the variable, here the data type is checked during compiling so debugging is much simpler...whereas Dynamically typed languages don't do the same, the data type is checked which executing the program and hence the debugging is bit difficult.

Moreover they have a very small difference and can be related with strongly typed and weakly typed languages. A strongly typed language doesn't allow you to use one type as another eg. C and C++ ...whereas weakly typed languages allow eg.python

人心善变 2024-08-13 04:11:50

静态类型

在运行时之前检查类型,以便可以更早地发现错误。

示例 = c++

动态类型

在执行期间检查类型。

示例=Python

Statically Typed

The types are checked before run-time so mistakes can be caught earlier.

Examples = c++

Dynamically Typed

The types are checked during execution.

Examples = Python

离线来电— 2024-08-13 04:11:50

动态类型编程,允许程序在运行时更改变量的类型。

动态类型语言:Perl、Ruby、Python、PHP、JavaScript、Erlang
输入图片这里的描述

静态类型,意味着如果您尝试将字符串存储在整数变量中,它不会接受它。

静态类型语言:C、C++、Java、Rust、Go、Scala、Dart
输入图片此处描述

Dynamically typed programming that allows the program to change the type of the variable at runtime.

dynamic typing languages : Perl, Ruby, Python, PHP, JavaScript, Erlang
enter image description here

Statically typed, means if you try to store a string in an integer variable, it would not accept it.

Statically typed languages :C, C++, Java, Rust, Go, Scala, Dart
enter image description here

调妓 2024-08-13 04:11:50

动态类型语言有助于快速构建算法概念的原型,而无需考虑需要使用哪些变量类型(这在静态类型语言中是必需的)。

dynamically typed language helps to quickly prototype algorithm concepts without the overhead of about thinking what variable types need to be used (which is a necessity in statically typed language).

狼性发作 2024-08-13 04:11:50

动态类型语言:

在 javascript 中(如果你知道),我们有两个数据类型关键字来定义变量名称:letconst(2015 年之前)只有一个 var)。

在Python中,甚至没有用数据类型关键字定义变量的概念。

但计算机内存或数据库系统中不存在 var、let 或 const 这样的东西。我们有 int、char、bigint 等。

那么,你明白了吗?作为程序员,我们不会在 JavaScript、Python、php、kotlin 等语言中定义变量数据类型,当代码在浏览器中运行(对于 js)或在服务器中解释(对于其他语言)时,解释器会决定应该使用什么数据类型根据变量中存储的数据分配给变量。

这个概念主要被解释/脚本语言所遵循,并且它在程序执行过程中会导致大量错误。这就是为什么你的 JavaScript 程序经常崩溃。

这在编程中被称为动态类型。

静态类型语言:

如果您曾经用 c、c++、java、go 或 rust 等语言编写过一些东西,您会发现,在编写代码时,我们会在变量名称之前提到变量的数据类型。

例如,在c和c++中,我们这样定义变量:int a = 1; char b = "a";

因此,作为程序员,我们有责任为变量分配数据类型。听起来很酷。

确实是……

这个概念通常是中低级语言所遵循的,并且可以显着减少因小错误而导致的错误。

这个概念称为静态类型

Dynamically typed languages:

In javascript (if you know), we have two data type keywords to define variable names: let and const (before 2015 there was only one var).

In Python, there is not not even a concept of defining variables with data type keywords.

But there is no such thing as var, let or const in computer memory or database systems for that matter. There we have int, char, bigint, etc.

So, you understand? as programmers, we dont define variable datatype in language like- Javascript, python, php, kotlin, etc, when the code run in browser (for js), or interpreted in server (for others), then the interpreter machine decides what datatype should be asssigned to a variable according to what data is stored inside it.

This concept is mostly followed by interpreted/scripting languages, and it causes a good number of bugs during the program's execution. That's why, you javascript programs breaks too often.

This thing is known as dynamic typing in programming.

Statically typed languages:

if you ever make something in languages like c, c++, java, go, or rust, you'll see, while writing code, we mention the datatype of variable before its name.

for example, in c and c++, we define variables like this: int a = 1; char b = "a";

So, as a programmer, we are responsible for assigning datatype to the variables. Sounds cool.

It really is...

This concept is usually followed by low/middle level languages, and significantly reduces the bugs caused by small mistakes.

This concept is known as Static Typing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文