Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Don't forget about type synonyms. ComplexDataStructure might be better called FilesystemAffinityMap. In general, if you have a bunch of functions which operate on ComplexDataStructure, you serve your future-self and others if you give your type signatures stronger semantic meaning.

That said, the choice of a C++ map as your example is unfortunate but illustrative. :)

The bog-standard mapping type in C++ is std::map, which has a method like this:

    T& operator[]( const Key& key );
One might think, based on the type and how this works in other programing languages and even from reading other people's code, writing `mymap[foo]` would just be an access. But it's not! If the `key` is not in the map, it inserts an item T, presumably calling the default constructor.

It's a good example of how, in general, the semantics of a lookup for a non-existent key varies by language. You have to use std::map::find() in C++, which returns an iterator which will equal std::map::end(). Python generates a KeyError exception (!). In Ruby and Clojure, you get nil, but note that you can have nil values in a map. :) Java returns null.

The Haskell signature for lookup is this:

   k -> Map k a -> Maybe a
What's going to happen is encoded in the type system. In general Haskell is good about this; Maybe indicates possibility of failure, lists suggest nondeterminism, etc.

That said, as others have pointed out, Haskell functions often end up being really generic. The language sort of pushes you in the direction of not specializing on types but rather putting looser restrictions, like typeclasses, on them. Type synonyms can help, too, as mentioned above.



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

Search: