Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what languages references are non-nullable by default?

Out of interest, I want to read about languages that are designed like this. Haskell is one, right?

I am talking about languages that does this, but also has compiler support to catch issues like if it's nullable, then you have to have appropriate cases, handling to compile, etc.

Also is it only a concept that's in functional programming? Does it also exist in some OO languages?

like image 488
Joan Venge Avatar asked Mar 07 '11 21:03

Joan Venge


3 Answers

Just to answer the first part of your question, you're right that Haskell doesn't have a special 'null' value that can be of any type.

If you want this behaviour, you have to change the return type of your function. Typically, you use the Maybe type for this, so for example:

safeDiv :: Float -> Float -> Maybe Float

safeDiv a b
    | b == 0    = Nothing
    | otherwise = Just (a / b)

This says that safeDiv takes two Floats and returns a type Maybe Float. In the body of the function, I can then return Nothing if b is zero, otherwise I return Just (a / b).

The key point is that your type signature explicitly marks whether your function can return Nothing or not, and any caller will be forced to handle the two possible cases in some way.

Haskell does, however, have Exceptions which can be thrown and caught. For pure functions it is preferred to return a Maybe value instead of just throwing an error, but even some Prelude (base library) functions are unsafe. For example, head, which returns the first element of a list, throws an error if the list is empty, instead of returning a value wrapped up in Maybe.

like image 117
chrisdb Avatar answered Oct 24 '22 05:10

chrisdb


Any of the ML-derived languages (of which Haskell is one) work like this, including SML and F# (although null can leak into F# from .NET interop). Scala also generally shuns null but the fact that it sits on top of the JVM makes it less strict about it than some other languages.

like image 42
munificent Avatar answered Oct 24 '22 06:10

munificent


You will find that Nullable is a matter of definition.

Most languages can be seen to have nullable pointers but not nullable values. Also, many languages provide a special null/nil-object with which variables are initialized automatically; would you count this as nullable?

On the one hand it is a special value distinct from all the values the variable normally holds (e.g. numbers), and is from that perspective the same as if you work with only pointers to numbers (nullable).

On the other hand this null/nil-object is a real object with a real class (in class-based-OO languages) and will understand many messages you send to it like asString(), so since it is a real object it is not a "null" in the strictest sense right?

like image 31
Bernd Elkemann Avatar answered Oct 24 '22 06:10

Bernd Elkemann