Sam (l33tminion) wrote,
  • Mood: cheerful

Haskell Rocks!

I've been messing around with Haskell lately, and while I am still a total beginner, I'm greatly enjoying it. If brevity is the soul of wit, Haskell is a very witty programming language indeed (and it's humor is quite comprehensible, compared to something like K). For example, the following is a (sort of) quick sort implementation:
qsort []     = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
The following is a program that takes a list of words on standard input and shows all the groups of anagrams (created with heavy borrowing of code from here):
import Control.Arrow ((&&&))
import qualified Data.Map as M
import Data.Char (isAlpha)
import Data.List (sort)

clusterBy f = M.elems . M.fromListWith (++) . map (f &&& return)
signature = filter isAlpha . sort
anagrams = filter ((> 1) . length) . clusterBy signature
main = (mapM_ print . anagrams . lines) =<< getContents
All functions are strongly typed (but with a huge degree of polymorphism (functions can take inputs of more than one type)). This typing is done intelligently, so you don't have to explicitly create type signatures for your functions unless you want to (for example, I could note that anagrams takes a list of strings and returns a list of lists of strings by adding anagrams :: [String] -> [[String]] before the function declaration, but this is already defined automatically). Functions can be defined in terms of pattern matching, as in the quick sort example above. And all functions are curried (takes parameters in sequence, returning the modified function) automatically, so you can do things like this:
sum = foldr (+) 0
  -- so that sum [1,2,3] -> 6
increment = (+) 1
  -- so that increment 3 -> 4
Tags: programming
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded