Posts

Showing posts with the label haskell

Nano chess engine at 19 lines

I've minified  bkil-open: edu/ai/nanochess.hs  to 19 effective lines of code in Haskell, and I'm running out of ideas. The goal was to construct a tiny snippet of code that illustrates a real chess engine instead of the ever boring 8-queens. It still wouldn't fit on a black board properly without further pruning. At the same time, trivial concurrency has been introduced to bkil-open: edu/ai/minichess.lhs , which seems to give it a linear boost. My next step in the area is to add interaction and eventually introduce a more advanced algorithm like alpha-beta to gain playable speed on a full board with complete rules.

Raincat, the incredible Haskell physics game

It was developed by CMU students, inspired by TIM, The Incredible Machine . Here's a short video clip of the cute game mechanics . I've discovered this pearl when browsing the Open Source Versions of The Incredible Machine wiki at project Butterfly Effect.

My programming language usage

In recent months, I've been developing Python (Geany, Netbeans), BASH (gedit, Geany) and a bit of HTML/Javascript (Netbeans, Geany) for work, Java (Eclipse) for coursework, Erlang (Emacs, sometimes Geany) and a bit of Emacs LISP (Geany) for labwork, and Haskell (Geany) for my own needs. I have also refreshed my Logo (Geany) skills recently to refactor two of my homeworks. I will move to C++/Qt/FFmpeg/SQLite (Qt Creator) again in the upcoming days for some time. I have dug into Gnome's Genie (and Vala) and will write a short overview of the language soon. That's 8-10 languages at my fingertips, but a few more aren't deep down below either, like C (you never forget the horror), Ada (hard to forget the beauty), Pascal (need to find a way to convert to Ada), Eiffel (have seen it, but no professional coding done in it yet). Sadly, I'm not allowed to share my Python code, and some of my more interesting BASH scripts. You also can't enjoy some unpublished parts of Refa...

OCaml vs. Haskell

Do you prefer laziness or ease of compiler implementation and proof of correctness? Haskell feels very comfortable to me, and I can write some beautiful code in it. Laziness could introduce some complexity to reason about temporary memory usage. It's the same reason I like Erlang: quick, dirty, but also elegantly minimalistic and predictable. I haven't tackled OCaml ( yet ;->). Do you think it worths it? OCaml vs. Haskell discussion at Y-Combinator Haskell performance is on par with OCaml (shootout.alioth.debian.org) do note, that the Haskell compiler and solutions have evolved since then

Install Hugs under Puppy Linux to program Haskell

Hugs is a nice little interpreter if you'd like to try out the language Haskell. It has few dependencies and it requires moderate resources to run. The download for a minimal install is less than 1.5MiB in size. If you have an operating system with package management, you can simply install the package 'hugs', or 'hugs98'. For example, on Debian-based systems (including Ubuntu) this amount to simply running: aptitude install hugs On distributions without a decent package manager (like Puppy Linux), you can install the Debian packages manually (refer to your distribution for details, but it usually involves clicking on each downloaded package or typing dpkg -i name.deb ). You first need to select a Debian major distribution version which matches with the versions of libraries on your system. On the Pupeee (Puppy 4.3) I had been using till now, choosing Lenny seems to work fine. So I've downloaded each i386 version from a mirror close-by of the following packages:...

Elementwise processing 2.1 for common keys in Haskell

Here's a neat little utility function which I commonly find useful. ef2_1 :: (a -> a -> a) -> (a -> a -> Bool) -> [a] -> [a] -> [a] ef2_1 = ef0 [] where  ef0 zs f lt (x:xs) (y:ys) | lt x y = ef0 (x:zs) f lt xs (y:ys)  ef0 zs f lt (x:xs) (y:ys) | lt y x = ef0 (y:zs) f lt (x:xs) ys  ef0 zs f lt (x:xs) (y:ys) = ef0 (f x y:zs) f lt xs ys  ef0 zs _ _ xr yr = reverse $ xr ++ yr ++ zs main = print $ ef2_1 (\x _->x) (\(x,_) (y,_)->x<y) d1 d2 where  d1 = [(1,9), (3,8), (4,7), (5,6), (7,5)]  d2 = [(2,5), (4,4), (6,3)]

Can you guess which conjecture these try to test?

let f l 1=l++[1];f l k|mod k 2==0=f(l++[k])(div k 2);f l k=f(l++[k])(3*k+1)in putStr $ unlines $ map (show . f[]) [1..11] let f l 1=reverse(1:l);f l k|mod k 2==0=f(k:l)(div k 2);f l k=f(k:l)(3*k+1)in putStr $ unlines $ map (show . f[]) [1..11] let f 1=Nothing;f k=Just(g k,g k);g k|mod k 2==0=div k 2;g k=3*k+1 in putStr $ unlines $ map (show . \n -> n:unfoldr f n) [1..11] let f 1=Nothing;f k=let x=(if mod k 2==0 then div k 2 else 3*k+1)in Just(x,x)in putStr $ unlines $ map (show . \n -> n:unfoldr f n) [1..11]

Haskell IDE

Gtk+: Leksah - Haskell IDE in Haskell built on Gtk+ and gtk2hs ( HaskellWiki: Leksah ) Eclipse : EclipseFP - functional programming support for Eclipse (Installation experience and comments: 1 , 2 ) Emacs : Haskell Mode for Emacs from Svein Ove Aas (previous maintainer was Stefan Monnier: 1 , 2 ) (TODO: is (setq haskell-font-lock-symbols 'unicode) the default?) , MMM (Multiple Major Modes) Mode for Emacs , scion-lib Haskell IDE library , HaRe -- The Haskell Refactorer Vim : Haskell mode for Vim , Superior Haskell Interaction Mode (SHIM): GHCi integration for VIM , Vim as a Haskell IDE, first steps illustrated tutorial, scion-lib Haskell IDE library , HaRe -- The Haskell Refactorer And of course we all know what xkcd: Real Programmers use. I'm eagerly awaiting your feedback!

Converting between Bird-literate and plain Haskell

Literate programming is a good idea, and there exist many creative ways in which you could take advantage of it, like one described in Literate Haskell with Markdown and Syntax Highlighting . However, if you're using the text editor Geany version 0.18, you will be faced with a bug that makes it unable to interpret Bird-style literate source. As a simple fix, I provide two programs to convert between simple Bird-literate and non-literate source code. You could also convert your Bird-literate to TeX-style . # bird_lhs2hs sed '   s/^>//   t   s/^ *$//   t   s/^/-- /  ' in.lhs > out.hs # hs2bird_lhs sed '   s/^-- //   t   s/^ *$//   t   s/^/> /  ' in.hs > out.lhs

FreeArc - advantage of developing in Haskell

FreeArc, a great performing free software archiver written in combined Haskell/C

Haskell for embedded: C output, compilers, monads, Timber

Tricks to use Haskell for developing embedded systems: Re: [Haskell-cafe] compilation to C, not via-C - question involving if you could output prettier C (answer: YHC/LHC or monadic generators) CUFP 2008 Program - see Controlling Hybrid Vehicles with Haskell by Tom Hawkins, Eaton Corporation TIMe - eMBEdded - Reactive - a promising O'Haskell inspired strict embedded research language

Simple Pascal-triangle implementations

-- The first version can output a row of Pascal's triangle : import System.Environment(getArgs) pas 0       = [1] pas n | n>0 = let l = pas (n-1) in zipWith (+) (0:l) (l++[0]) main = do     [s] <- getArgs     print . pas $ read s -- The second revision can output a certain number of rows of the triangle: import System.Environment(getArgs) pas = iterate nextline [1] where     nextline l = zipWith (+) (0:l) (l++[0]) main = do     [s] <- getArgs     putStr . unlines . map show $ take (read s+1) pas -- And the last monolith solves a very simple homework assignment: import Data.List(intersperse) import System.Environment(getArgs) pas 0 = [1] pas n = let l = pas (n-1) in zipWith (+) (0:l) (l++[0]) strPas s = do     let n = read s     if n<0 || n>30 then         fail ...

Haskell optimization

edit2: added Real World Haskell link via Mr. baja :-) (edit1: tiny formatting correction) Chapter 25. Profiling and optimization from Real World Haskell by Bryan O'Sullivan, Don Stewart, and John Goerzen Acovea (Analysis of Compiler Options via Evolutionary Algorithm) - this is compatible with virtually all compilers Evolving faster Haskell programs via Acovea - 18% runtime reduction in one case, even for hand-tuned code! Haskell as fast as C: working at a high altitude for low level performance - this shows that introducing higher abstractions shouldn't automatically cause a slowdown Map fusion: Making Haskell 225% faster a similar article HaskellWiki: Performance/GHC optimization tricks and tips to apply by hand And a little reminder about the secret option used during our discussion on performance analysis: ghc -ddump-simpl $FILE > core.txt

The code escaper I use for this blog

Edit: numeric HTML escaping added (not Unicode compliant); minor refactoring (readFile and writeFile improvement, some renames) Previously, I had two bash scripts for this task, but ironically, I had escaping problems within them, so I've decided to go for the clean, well-written solution below. I usually patch issues like this in my scripts, but sometimes it just isn't worth it. Fixing these is more akin to juggling, than to real bug fixing. So this is what I use from now on: import Prelude hiding(readFile,writeFile) import qualified Prelude(readFile,writeFile) import System.Environment(getArgs) import Data.List(group) import Data.Char(ord) data FileName = FileName String readFile (FileName s) = Prelude.readFile s writeFile (FileName s) d  = Prelude.writeFile s d toHtml = concatMap code where     code '&' = "&amp;"     code '<' = "&lt;"     code '>' = "&gt;"     code c | ord(...

Program Erlang/OTP without the syntax quirks

I think I can say that you can be pretty comfortable with Erlang after a while, but you never forget how clear and conscious Haskell (or Scala, etc.) code is compared to that. If only you needed to type less punctuation and if it had static types... Anyway you can both have your pie and eat it according to some projects: Targeting a Haskell compiler for the Erlang BEAM The following were newbie hacking attempts at transforming Haskell syntax to Erlang syntax at the source level: The Haskerl index of some related mails [erlang-questions] Any recent progress on Haskerl? (the project page blog.tornkvist.org seems to be unavailable at the moment)

Haskell vs. Erlang vs. Scala

Comparing Haskell , Erlang and Scala by way of examples and intelligent analysis: An Example Syntax in Haskell, Erlang and Scala (blogtrader) The multicore crises: Scala vs. Erlang (a detailed and informed analysis by Niclas Nilsson and nice follow-up discussion) Programming language shootout game on x86-64: Haskell Programming language shootout game on x86-64: Erlang Programming language shootout game on x86-64: Scala Of course, all three are great languages, with Haskell having an edge over the competition in pureness and syntax neatness, Scala in technology, experience transfer and sometimes syntax, while Erlang has the edge over provenly great concurrency, scalability and a beginner-friendly straight-forward syntax - in exchange for being a dynamic language. Expect to read more introductory articles on Scala in the future.

Playing with lambda elimination and point-free style

It was a long time since I've last played with Haskell, so I decided to do a bit of lambda elimination as an exercise. let f=(\x y->x++y);g=(\x y z->x++y++z)in f(g "1""2""3")"4" let f=(++);g=(f.).f in f(g "1""2""3")"4" let f=(++);g=(f.).f in (f(g "1""2""3"))"4" let f=(++);g=(f.).f in (f.(g "1""2"))"3""4" let f=(++);g=(f.).f in (f.((g "1")"2"))"3""4" let f=(++);g=(f.).f in ((f.).(g "1"))"2""3""4" let f=(++);g=(f.).f in ((f.).g "1")"2""3""4" let f=(++);g=(f.).f in (((f.).).g)"1""2""3""4" let f=(++);g=(f.).f;h=((f.).).g in h"1""2""3""4" let f=(++);h=((f.).).(f.).f in h"1""2""3""4" let ...

Chopping a long string into smaller ones toy

I made a great tool I can't do without from now on! ;-D Update#1: added null string checking, renamed "i" to "s". Update#2: upgraded output format, added BASH version! Here's the Haskell source code: import System.Environment(getArgs) import Data.List(unfoldr,intersperse) chop k | k>0 = unfoldr f where  f [] = Nothing  f s  = Just $ splitAt k s main = do  [k,s@(_:_)] <- getArgs  let out = show . concat . intersperse " "      res = chop (read k) s  putStrLn $ "filter(/=' ')" ++ out res Typing: ./chop.hs 27 http://bkil.blogspot.com/2009/05/chopping-long-string-into-smaller-ones.html Gives: filter(/=' ')"http://bkil.blogspot.com/20 09/05/chopping-long-string- into-smaller-ones.html" Or if you prefer, you could alternatively opt for the following BASH routine: main(){  printf 'echo "'  printf "$2"|sed -r "s~.{$1}~& ~g"  echo '"|sed "s~ ~~g"' } This one...

Quine in Erlang

How could I have forgotten about the friend of mine who's fond of Erlang? :-D -module(q). -export([s/0]). s()->io:format("~s~p.\n",[p(),p()]). p()->"-module(q).\n-export([s/0]).\n\ns()->io:format(\"~s~p.\\n\",[p(),p()]).\n\np()->". Here's another one for the Eshell REPL: fun(P)->io:format("~s\n~p).\n",[P,P])end( "fun(P)->io:format(\"~s\\n~p).\\n\",[P,P])end("). And as I know he's also in love with LISP, here's a Haskell variant rewritten in that spirit: (\ (x)-> ((++) x (show x)))"(\\ (x)-> ((++) x (show x)))"

Quine in Haskell

I've constructed a neat little quine in Haskell, the popular research language we all adore. ;-) It's so short, I could have pasted it right into the title! :-D putStr(p++show p)where p="putStr(p++show p)where p=" That's what I like about Haskell: the solutions you write in it are usually elegant, conscious and close to the problem space in representation. You read the above source as follows: print out the program accompanied by a quoted (shown) version of the same, where the program is just what I said. Can you put it any simpler than that?! I've first started on a traditional route by introducing constants for backslash, quotation mark and all that, until I've realized how foolish I was. As you may have already known, Haskell has a handy function called 'show' that does all quoting for you. I've been using that all over the place if you have read any of my sources, so I'm not sure why it slipped my mind. Sometimes we overlook the most o...