Showing posts with label Haskell. Show all posts
Showing posts with label Haskell. Show all posts

Sunday, October 17, 2010

Install Haskell environment on Gentoo

I just installed Haskell environment (ghc 6.12.3) on a Gentoo Linux system(2.6.31-gentoo-r10). Since the package system of Gentoo is not quite compatible with cabal, I choose to install the binary version of ghc and then use cabal to install everything else. The first problem is a complain going like this: "gtk2hsC2hs is required but it could not be found". It turns out that we need to cabal install gtk2hs-buildtools before moving on.

Another complain repetitively made by cabal is "can't load .so/.DLL for: readline (/usr/lib/libreadline.so: invalid ELF header)", easily reproducible by issuing "ghci -package readline". After some investigation, it turns out to be due to a Gentoo policy.

To work around the problem, I assumed root privilege to use the following script, which basically restores libraries under /usr/lib/ to be true ELF files instead of symbolic links.

#!/bin/env python
import os
cmd = "mv /usr/lib/lib%s.so{,.old};ln -s /lib/lib%s.so"%(i,i)
for i in ["ncurses","ncursesw","readline","z"]:os.system (cmd)

Lazy list is Python generator

Functional programmers often miss lazy list when coding in a popular language. In some circumstances, they can make do with Python generators. An even better news is that from 2.3, Python provides  itertools library, which contains the old friends: cycle, repeat, takeWhile, dropWhile ... such that
takeWhile (<10) [1..]
translates to
>>> list(takewhile (lambda x:x<10,count(1)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Now if the library is short for your need, we can resort to yield statements in python. Suppose we want to enumerate ways of splitting a list into two parts.
>>> list(splits ([1,2,3]))
[([1, 2, 3], []), ([2, 3], [1]), ([1, 3], [2]), ([3], [1, 2]), ([1, 2], [3]), ([2], [1, 3]), ([1], [2, 3]), ([], [1, 2, 3])]
In Haskell it will be
splits [] = [([],[])]
splits (x:xs) = concatMap expand $ splits xs
                where expand (a,b) = [(x:a,b),(a,x:b)])
In Python it will be
def splits(l):
    if l==[]:yield ([],[])
    else:
        x,xs=l[0],l[1:]
        for (a,b) in splits(xs):
            yield ([x]+a,b)
            yield (a,[x]+b)
Quite literate, isn't it!