Posts Tagged: functional programming

Sep 15

Better Scala pattern matching with erasure

With many beautiful and some rather repulsive elements in Scala pattern matching is definitely the former. Unfortunately, due to Scala’s reliance on the JVM it suffers from [type erasure].

Scala’s latest editions have an improved reflection facility that allows you to retain types and then use them at runtime.

Below is an example of using TypeTag to pattern match types at various depths. [I’m actually pattern matching Java’s collection types here].

Oct 10

Learning Haskell (Part 1)

So my friend Davis Ford decided to start a Haskell study group in Grosse Pointe, MI. Our first meeting was yesterday, and 4 people attended. This isn’t bad, considering that most IT folks don’t live nearby and the fact that it’s Haskell :-). I think we might be able to get 6+ at the next meeting and hopefully more at some point.

We had a really good start yesterday. We decided to read Ch. 1-4 of LearnYouAHaskell before the meeting and then discuss the relevant topics. Here are some of the n00b things we talked about:

  • function declarations and definitions
  • function argument destructuring and polymorphic dispatch
  • implemented recursive product function and quick sort
  • logging, which turned into having pure/impure function mixture

So our quicksort implementations turned out to be such:

One thing that I still haven’t concretely figured out is the fourth bullet point, logging. Basically I wanted to perform logging while say calculating a product. Evidently you can either have a destructive function, which performs/returns IO operation(s), or a pure function. Mixing both doesn’t seem to work.

Something as simple as:

printSomething' = do 
  putStrLn "test"
  return (1 + 1)

Didn’t work, yielding this error:

Occurs check: cannot construct the 
infinite type: b = IO b
      Expected type: b
      Inferred type: IO b
    In the first argument of return', 
    namely((product' xs) * x)'
    In the expression: return ((product' xs) * x)

I was able to find information discussing doing this through an IO Monad, but am yet to actually construct a working example. Seems like too much work for something as simple, but it might just be that I’m misunderstanding something due to lack of Haskell knowledge. Off to learn more this week and I’ll post a working hybrid function example once I get it worked out.