Return type overloading in Haskell

Function overloading is very common in many programming languages like C# but most of the languages that I have used only support overloading based on function arguments. For example in C# there are several overloads on the String.IndexOf function where each overload differs in what argument type it accepts.

image

This overloading support doesn’t extend to function return types. If an additional overload is added (bool String.IndexOf(char)) that returns true if the character is found in the string the compiler will give an error like “Type ‘String.IndexOf’ already defines a member called ‘IndexOf’ with the same parameter types”.

The Haskell Way

Haskell supports both function argument type and return type overloading using type classes.

Given two functions indexOfExists and indexOfPos.

indexOfPos value str =
  case elemIndex value str of
    Just i -> i
    Nothing -> -1

indexOfExists value str =
  case elemIndex value str of
    Just _ -> True
    Nothing -> False

I can create a type class which defines an indexOf function and add both indexOfPos and indexOfExists to this class.

class StringOps a where
  indexOf :: Char -> String -> a

instance StringOps Int where
  indexOf value str = indexOfPos value str

instance StringOps Bool where
  indexOf value str = indexOfExists value str

Now when I use the indexOf method Haskell will figure out whether to use indexOfExists or indexOfPos based on the return type.

*Main> indexOf 'e' "matthew" :: Bool
True
*Main> indexOf 'e' "matthew" :: Int
5

 

Real World Use Case

This functionality is used beautifully in the Text.Regex.Posix module.  This module contains regular expression functions and in particular exposes the =~ operator. This operator lets you match a regex pattern against a string and its behavior is overloaded based on its return type. This is useful since whether you want to know if the regex matches, what the first match is or get a list of all matches you can just use the =~ operator and the return value type will match the code you write. Here are some examples of output from the =~ operator based on return type:

*Main Text.Regex.Posix> "mississippi" =~ "i(s|p)" :: Bool
True

*Main Text.Regex.Posix> "mississippi" =~ "i(s|p)" :: String
"is"

*Main Text.Regex.Posix> "mississippi" =~ "i(s|p)" :: Int
3

*Main Text.Regex.Posix> "mississippi" =~ "i(s|p)" :: (String,String,String)
("m","is","sissippi")

*Main Text.Regex.Posix> "mississippi" =~ "i(s|p)" :: (Int,Int)
(1,2)

Posted in Haskell | Leave a comment

Snippet Designer 1.4.0 Released

Snippet Designer 1.4.0 has been released. You can get it from its CodePlex page, on the Visual Studio Gallery or through the extension manager in the Visual Studio IDE.

Snippet Explorer Changes

image

  • Reworked  language filter UI to work better in the side bar.
  • Added result count drop down which lets you choose how many results to see.
  • Language filter and result count choices are persisted after Visual Studio is closed.
  • Added file name to search criteria.
  • Search is now case insensitive.

Snippet Editor Changes

image

  • Added menu option for the $end$ symbol which indicates where the cursor should be placed after the snippet is inserted.
  • Added menu option for the $selected$ symbol which indicates where the selected text in the editor should be placed after the snippet is inserted. This requires a snippet type of SurroundsWith.
  • Exporting a snippet from the editor will now automatically escape “$” characters.
  • Existing snippet replacements will be detected and added when you paste a code snippet into the snippet editor.

 

For the complete change list see the issue page.

Posted in Open Source, Snippet Designer | 3 Comments

DiffPlex 1.2 Released

I released version 1.2 of the DiffPlex library on both CodePlex and Nuget. This new version contains a few notable changes.

  1. A new class called InlineDiffBuilder which makes it easier to build inline diffs (the same way the existing SidebySideDiffBuilder enables side by side diffs).
  2. A new argument on the IDiffer interface which causes the diffing algorithm to ignore letter casing. (See work item)
  3. DiffPlex 1.2 now targets .NET 4.0 and Silverlight 4.0

 

You can download the new version at the DiffPlex home page as well as contribute code/ideas to the project.

Posted in DiffPlex, Open Source | 1 Comment

Refactor now, not later

Imagine this situation (one I’ve been in too many times): you have been working on a piece of code and have created a complicated/intricate function. You look over your work and realize it is an ugly mess; the function is over 100 lines long and a tangled jumble of logic. However, it works and is tested; you are tired of working on this function since you have already spent so much time on it. At this point you consider two options: refactor the code or leave a comment indicating that this code should be refactored.

// This code needs refactoring

// Refactor this later
void SomeoneRefactorMeSinceMyCreatorHatesMe()
{
 // Save me
}

It is tempting to leave a comment to refactor and move on, but this decision is supported by some problematic assumptions.

1. I will fix it later

You won’t.

Once a developer puts the comment “refactor this later” on a function and checks it in he has already washed his hands of the function. I often see comments like this. Sometimes they stay in the code base for years without anyone ever addressing them. Often the original developer has long left the project but these comments remain. When asked about them, the author usually responds, “OH YEA! I forgot about that…”.

Not surprising; that comment expresses the developer’s disdain for the job that needs to be done. It follows that this developer will “forget” to come back and fix it. Is this cognitive dissonance rearing its ugly head? The developer knows he doesn’t want to work on it and thus conveniently forgets to return to it.

2. Someone else will fix it

They won’t.

If the author is unwilling to clean up his mess it seems unlikely that anyone else will jump at the opportunity. Plus, code that needs refactoring will be much harder for another developer to comprehend. (Even the author’s understanding of the code will wane the longer he waits to fix it.)

Leaving a comment to refactor is also disrespectful to other developers on the project. Instead of taking my garbage to the curb I carry it into work and dump it on another developer’s desk. If you realize your code is bad you should respect other developers enough to not force them to deal with it.

3. My time is better spent increasing functionality

It isn’t.

“Because this function works and there are other features to complete, refactoring now is a waste of time.” This thought devalues code quality in favor of functionality, which may seem like a good idea now but in the long term will hurt the project. When a function like this is left in the code it causes the entire code base to slowly creep towards an unmaintainable state. This is a concept called software rot. When the next developer needs to work with this function it will take him longer to understand and update, resulting in future features which take longer to complete. Pieces of code exist that developers *dread*. Work is delayed because developers avoid the messy code.

Refactor Early, Refactor Often

Quality of code is vital to a healthy software project. It may be scary to tell your project manager you will not ship functionality because of refactoring needs, but a good manager will appreciate that doing so now is better in the long run, and relying on a future fix is detrimental to the project. While it may feel more productive to move away from one piece of laborious code, in the end take pride in clean and easily understood code. Your team will thank you.

Posted in Software Development | Leave a comment

Regex Hero: Free online regular expression tester

A regex tester is one of those tools developers often need. I used many different ones over the years and  have never settled on one that I really like.  I have seen some paid ones that looked promising but I hoped to find a good free one. A few months ago I came across Regex Hero which is an online Silverlight based regex tester for .NET.  It has both a free and a paid version ($15) . I have not used the paid version so my description is based solely on the free version.

Regex Hero has all the standard features you expect with a regex tester.

1. Syntax highlighting

2. Syntax checking

3. Real time matching, replacing and splitting against a target string

Regext tester

4. Group matching

image

 

In addition to these pretty standard features Regex Hero has a couple really nice additional features.

1. Context sensitive completion menus

image

 

2. Generate C#/VB code from your regular expression

image

 

3. Save your regexes online and access from any computer

image

 

This tool is definitely a steal for a price of $0.  If anyone has tried the “pro” features of Regex Hero I would love to hear what you think about it but for now I am more than satisfied with the free version of this great tool.

Posted in Regular Expression, Tools | Leave a comment