4 ms·
My dabbling in Haskell has given me a new perspective on null. Previously, to me "null" was just "that other value that a variable gets if the function doesn't
by losvedir 15y ago
My dabbling in Haskell has given me a new perspective on null.
Previously, to me "null" was just "that other value that a variable gets if the function doesn't work or something unexpected happens." It was useful if ugly. I didn't fully grasp how much that null possibility permeated my code, since I didn't know any other way.
However, in Haskell, if something is an integer, it really is an integer of some sort. Null is not allowed.
So if you're writing a function that works with numbers, you really have to think about what are valid inputs and outputs. If you're working with a function whose domain really is all integers, then you can indicate that with a Integer -> Integer function, and you're on rock solid ground.
However, if you're writing a function like, e.g. square root, where the domain is not all integers, then you have to worry about what happens if you get a negative one. Now you can choose to bring in "null" as an allowable value, but it will have to be explicitly indicated and dealt with. Your function, for all the world to see, will be Integer -> Maybe Integer, and then any other function that uses that function will be forced to deal with the fact that a null might happen.
- timclark 15y agoThis is Haskell esoterica, any value can set as undefined an equivalent value to null. However, you never see code using undefined as null since Maybe a is so much clearer.
- jganetsk 15y agoundefined and null are quite different. It's impossible to test for undefined. You cannot expect (x == undefined) to return true. It would result in exception, in fact. You can only safely make a value undefined if you guarantee it won't be used.