Hacker News new | past | comments | ask | show | jobs | submit login

> Why does a statically typed langauge need "type inference"

   let suffix str = str ^ "mysuffix";;
   val suffix : bytes -> bytes = <fun>
Type inference in action: the OCaml toplevel displays the type of the 'suffix' function as something that takes a value of type bytes and returns a value of type bytes, without any type declaration (though obviously, the type inference system works in much more complex cases as well). You can write entire programs without a single type declaration.

Dynamic languages do not do type inference. They do duck-typing. The big difference is that OCaml will not let you write a program like:

    let suffixed_five = suffix 5
You will get:

    Error: This expression has type int but an expression was expected of type                                                           bytes
Python will not let you concatenate integers and strings, either, but will blow up at runtime.



Some dynamic languages, notably Ruby, use duck typing. Many tag all values with types, Lisps are an example. Tagged types allows a dynamic language to be strongly typed [dynamic/static is orthogonal to strong/weak typing, C being an example of weak static typing].

Type inference is syntactic sugar in most languages that allow it, and explicit type declaration is [almost?] invariably permitted. Of course, the price of omitting type declarations in code is the potential loss of clarity that comes anytime implicit communication is used in lieu of explicit statements of intent.


A nit: Dynamically typed languages do not all use duck-typing. Duck-typing is primarily concerned with the question: Does this object respond to this message/method or have this field? If the answer is yes, then we'll act as though it's whatever type we needed it to be. So duck has a quack() method and decoy_duck has a quack() method. decoy_duck is not, in fact, a duck, but it has enough of the duck behavior for what we need.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: