Archive for July, 2012

Sine oscillator in Yampa

July 30, 2012 1 comment

Yampa can be used to produce sound waves as illustrated here. In order to understand Yampa better I tried out the sine oscillator.

oscSine :: Double -> SF Double Double
oscSine f0 = proc cv -> do
               let f = f0 * (2 ** cv)
               phi <- integral -< 2 * 3.1415 * f
               returnA -< sin phi

sinTest = constant 0 >>> oscSine 1

embed sinTest (0.0, take 250 (repeat (0.01, Nothing)))

Plotting the result yields:


Ok. No problem so far.

Categories: Uncategorized

Haskell Graphics

The next step in my Haskell quest has been to display some graphics. I might add that I use windows and that I use Haskell platform 2012.2.0.0. After a bit of investigation I found this rather hairy description. Not too encouraging. At this point I had been fiddling around and I might have installed bindings for OpenGL and GLUT using cabal.

(?) cabal install OpenGL

(?) cabal install GLUT

At least the packages are among my installed packages when listing using

cabal list –installed


Anyhow, I decided to just give it a shot without installing anything – just to see what happened. I copied the source code for teapot.hs and compiled it using:

ghc teapot.hs


It actually compiled without any problems into teapot.exe but when run nothing happened. I figured that this might be due to a missing glut32.dll. I downloaded a precompiled version from here and placed the dll next to the teapot.exe and bang:


The application was up and running. Nice and simple. (Don’t know why it is called teapot though).

Categories: Uncategorized

Haskell Yampa

In my last post I mentioned that I had been looking at some Haskell libraries. Yampa has been my main interest. Using Yampa it is possible to define signals and signal processing functions. Signals are time varying functions and, for example, game ai behavior can be expressed using signals. I started out much simpler and here is my initial test:

import FRP.Yampa

add10 :: SF Int Int
add10 = arr $ (\x -> x+10)

gt20 :: SF Int Bool
gt20 = arr $ (\x -> x > 20)

composite :: SF Int Bool
composite = add10 >>> gt20

— arrow notation,
— requires -XArrows flag, GHC
add10ext :: SF Int Int
add10ext = proc x -> returnA -< x + 10

compositeExt :: SF Int Bool
compositeExt = proc x -> do
                 y <- identity -< x + 10
                 returnA -< y > 20

As suggested here primitive signal functions can be tested using the embed function. For example:

putStrLn $ show $ embed compositeExt (5, [(1, Nothing), (2, Just 17), (3, Nothing)])
— [False,False,True,True]

Categories: Uncategorized

Yet another Sudoku solver (in Haskell this time)

I have looked into some Haskell libraries lately. I have not used Haskell in a long time so I felt I needed to shape up and what could be a better exercise than writing a Sudoku solver. The entire source code is available on bitbucket but let me just walk through the important parts.

The board is represented using the following types:

type Cell = (Int,Int,[Int])
type Board = [Cell]

A cell keeps track of its row and column index along with the possible values that fit into the cell. A board is then simply a list of cells.

The solve method is invoked on a board and returns all possible solutions. It relies on back tracking.

solve :: Board -> [Board]
solve xs =
    let xs’ = propagateConstraints xs in
    if invalid xs’ then
    else if unique xs’ then
        let (r,c,vs) = leastAmbiguousCell xs’ in
        let xs” = filter (\(r’,c’,_)->not(r’==r&&c’==c)) xs’ in
        concatMap solve [ (r,c,[v]):xs” | v <- vs ]

The most important helper method here is the function for constraint propagation.

propagateConstraints :: Board -> Board   
propagateConstraints xs =
    [ cell |
       (row,col,vals) <- xs,
       let rowValues = getRow row col xs,
       let colValues = getCol row col xs,
       let blockValues = getBlock row col xs,
       let vals’ = vals \\ (rowValues `union` colValues `union` blockValues),
       let cell = (row, col, vals’) ]

Note that it is expressed entirely using a single list comprehension. Nice! List comprehensions in Haskell almost seem magical sometimes. Helper functions for row, column and block extraction are very simple:

getRow r c = unify . filter (\(r’,c’,_)->r’==r && c’ /= c) . singularOnly

getCol r c = unify . filter (\(r’,c’,_)->c’==c && r’ /= r) . singularOnly

getBlock r c = unify . filter (\(r’,c’,_)->bi==(blockIndex r’ c’) && not(r’==r && c’==c)) . singularOnly
               where bi = blockIndex r c

Finding the least ambiguous cell is also simple:

leastAmbiguousCell = minimumBy (\(_,_,vs1) (_,_,vs2) -> compare (length vs1) (length vs2)) . filter (\(_,_,vs)->length vs > 1)

Ok, that’s about it. Thanks for reading.

Categories: Uncategorized

Python-Embedded XML

Reading Python-Embedded XML and Test Automation on the code project got me thinking.

I do agree on (and I even think it might be fundamental):

An elegant solution is to separate a piece of test program into two parts: one to model the process and the other to model the data.

fscheck makes this distinction very clear. Considering the specific solution I think it is interesting but I can’t help but thinking that the payback for this complexity is too low. My test bench will have a direct dependency to the library (that includes two dlls) which in turn has a compile time dependency to boost and runtime dependency to python.
If tests are written in, using embedded xml would probably be just as nice.

Imports System.Xml.Linq
Module Program
    Dim rnd As New System.Random
    Dim globalCount As Integer = 0
    Function RoundRobin(list as String()) As String
        globalCount = globalCount + 1
        RoundRobin = list(globalCount Mod list.Length)
    End Function
    Function ExtraCredit(prob as Double) As String
        If rnd.NextDouble() < prob Then
            Return "Yes"
            Return "No"
        End If
    End Function
    Sub Main()
        Dim days As String() = New String() { "Mon 7am", "Tue 2pm", "Thur 9am", "Fri 1pm" }
        Dim xml As XElement =
                <StudentID>SID0000<%= String.Format("{0:000}", rnd.Next(100)) %></StudentID>
                <Class><%= RoundRobin(days) %></Class>
                <ExtraCredit><%= ExtraCredit(0.2) %></ExtraCredit>
        Console.Write("Press any key to continue . . . ")
    End Sub
End Module

Powershell users might like:

$i = 0;
function round-robin($l)
    return $l[$i % $l.Length]
function extra-credit($x)
    $r = Get-Random -Minimum 0 -Maximum 100
    if ($r -gt $x*100) { "Yes" } else { "No" }
    <StudentID>SID0000$("{0:000}" -f (Get-Random -Minimum 0 -Maximum 100))</StudentID>
    <Class>$(round-robin ‘Mon 7am’, ‘Tue 2pm’, ‘Thur 9am’, ‘Fri 1pm’)</Class>
    <ExtraCredit>$(extra-credit 0.2)</ExtraCredit> 

Powershell script can be evaluated from C#, or .NET, using System.Management.Automation but I do not think this pays back either. Of course, this is my personal opinion and others might think differently.

Categories: Uncategorized

Powershell ISE–Copy as html

Published a new project on codeplex for Powershell script to colored html conversion. This can be used to add a “copy as html” extension to the Powershell ISE. Hopefully it will save me some time the next time I reinstall my computer and, with a bit of luck, someone else find it useful too.

Categories: Uncategorized

Powershell: convert roman numbers to decimal

I picked up another code golf challenge. This time the task was to convert roman numbers to decimal numbers. Here is my result (~132 characters, function header excluded):

function Convert-RomanToDecimal($s)

Along with my test cases:

$testdata = @{
    # wikipedia
    "MCMXLIV" = 1944;
    # code golf test cases
    "MMMCCXC" = 3290;
    "MCMVII" = 1907;
    "MMCDXLVII" = 2447;
    "MMCMLXXXIV" = 2984;
    "MXCVI" = 1096;
    "MCMIV" = 1904;
    "MMDII" = 2502;
    "M" = 1000;
    "MMDLXXIX" = 2579;
    "MMMLXXXVIII" = 3088;
    "MMDCCXCIX" = 2799;
    "MMDVI" = 2506;
    "MMMDCCLVII" = 3757;
    "MMMCCLXXXIII" = 3283;
    "MCDXL" = 1440;
    "MMD" = 2500;
    "DCLI" = 651;   
$testdata.keys | % {
    $calculated = Convert-RomanToDecimal $_
    $expected = $testdata[$_]
    if ($calculated -ne $expected) {
        throw "Test failed since $calculated does not match $expected"

I guess it is not too hard to cut it down a bit further (or is it?). Anyway – I like the compactness of Powershell. Of course – when pushed this far – the result gets, erhmm, somewhat obfuscated…

Categories: Uncategorized