The expressiveness of Haskell – Substrings.

Earlier today I was talking with a colleague about extracting a substring of a string given the start and end indices. He showed me an implementation in Javascript and I wrote one in Java and then looked at the Java 8 implementation which I’ve pasted below.

If we reformatted this we’d have 6 lines of code.

Now for some Haskell… What is it we do when extracting a substring? For me, I think of it as taking the string, dropping the chars up to the start index and then from that getting chars up to the end index and then forgetting about everything after that. Here it is in Haskell generalised to work on arbitrary lists and not just strings.

I think that is beautiful in its simplicity and elegance.

Corner cases of index values are handled gracefully and the same function will work on any type – Strings, numbers…

Here’s some ‘bad index’ examples:

And on a list of Int

Short and Sweet!

Thanks for reading…

Leave a Reply

Your email address will not be published. Required fields are marked *

ˆ Back To Top