lunes, febrero 08, 2010

Simple "shuffle" in Haskell

I got tired of Amarok so I've been using mplayer from the console. The only problem was to shuffle the playlists. Being a little bored I decided to write a simple shuffle script in Haskell.

module Main where

import Control.Applicative ((<$>))
import System.Random (getStdGen, randoms)
import Data.Ord (comparing)
import Data.List (sortBy)


main :: IO ()
main = do
ls <- lines <$> getContents
gen <- getStdGen
let rs = randoms gen :: [Double]
mapM_ (putStrLn . fst) . sortBy (comparing snd) $ zip ls rs



This approach is the easiest to implement but unfortunately it isn't "perfect". A functional "perfect shuffler" is discussed by Oleg here.

Now I can just write:

diegoeche@multivac:/Music$ find . -name *.mp3 | ./shuffle | \
mplayer -playlist -