Languages with immutable variables by default, like Haskell
one thing that I find fascinating about Haskell is how functions and variables are the same. In most languages a variable holds a value while a function does something and then, eventually, returns a value. In Haskell you don't see this difference and after having used Haskell, falling back to more "traditional" programming where variables are different from functions or methods feels awkward. If I want to get a value, I shouldn't really worry about its origin, whether it is a constant value, a mutable variable or the result of a complex computation! In Haskell, variables are just 0-ary functions.
Many object-oriented languages have properties that feels a bit the gap.
Can anyone indicate any other language with a system similar to Haskell? I thought it was common to functional languages because of referential transparency, 开发者_开发知识库but I've seen it's not the case. In Lisp, for example, you have (defun)
to explicitly declare functions.
Can anyone indicate any other language with a system similar to Haskell?
Several languages have immutable variables (i.e. variables in the mathematical sense) by default:
- Haskell (obviously),
- Clean,
- Erlang,
- ML.
Others encourage this behavior via 'const' or 'val' declarations (Scala, C).
In many functional languages mutable values may only be introduced via explicit 'ref' or 'var' declarations.
In Clojure defn is just a macro to def. Vars are immutable and they hold values. Functions are just values just like any other kind of value. Whether a value actually is a function (Fn) is not important as whether that type of value implements the function interface (IFn).
To clarify the last point a Java primitive array is not a function. I may wish to treat it as a Clojure Sequence, I could create a wrapper type that allows me to present that interface (ISeq) over the primitive array. I could also have the wrapper type implement IFn and the primitive array could then be treated as a function as well.
(def x (wrap-prim-array ...))
(nth x 0) ; idiomatic random access
(x 0) ; used as a function
Don't forget Javascript.
var a = function(x) { return (x + 1) };
var b = a(1);
// b == 2 here.
is perfectly legitimate.
精彩评论