Feb 21, 2008

How to generate a random number in Scheme.

I couldn't find a function that generates a random number.
Instead, I make that function using "".

I wont to get current time for a seed.
But I couldn't a function for it.


(define (rand seed)
(let ((x seed))
(lambda ()
(set! x (remainder (+ (* 13 x) 5) 24))
x)))



(define a (rand 1))

(display (a))
(newline)
(display (a))
(newline)
(display (a))
(newline)



18
23
16

Feb 20, 2008

Closure of Scheme.

The simplest closure sample of Scheme.


(define (f x)
(let ((y x))
(lambda ()
(set! y (+ y 1))
y)))




> (define a (f 1))
> (display (a))
2
> (display (a))
3
> (display (a))
4

Feb 19, 2008

Conditional branches of Haskell.

I'm studying Haskell.

Haskell has some conditional statements.

1. pattern matching

fact 0 = 1
fact n = n * fact (n-1)


2. guard

fact n | n==0 = 1
| otherwise = n * fact (n-1)


3. if

fact n = if n==0 then 1
else n * fact (n-1)


4. case

fact n = case n of
0 -> 1
_ -> n * fact (n-1)

Feb 18, 2008

I try Haskell.

I'll conduct study sessions at my office this week.
I learned the basics of Haskell for it.
It's interesting to be able to create an infinite list by delay evaluation.

Feb 17, 2008

Output Fibonacci number without recurrence.

It is possible to write a code for Fibonacci number without recurrence.
Alternatively the code include a loop.


def fib(n)
a, b, c = 0, 1, 0

n.times do
c = a
a = b
b += c
end

a
end

p fib(10)

Feb 16, 2008

Use closure for event handler.

This is a sample program.
A number displayed on a label increases when a button is clicked.


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.button1.Click += new EventHandler(button1_Click);
}

int num = 0;

void button1_Click(object sender, EventArgs e)
{
this.label1.Text = num.ToString();
num++;
}
}


This code uses a member field "num".


I rewrite this code using closure.


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.button1.Click += make_button1_Click(0);
}

EventHandler make_button1_Click(int num)
{
return delegate(object sender, EventArgs e)
{
this.label1.Text = num.ToString();
num++;
};
}
}


This code uses no member field.
Closure memorize the variable "num".

Feb 15, 2008

I tried F# programming.

F# code for Fibonacci number.

let fib n =
let rec fib_iter n a b =
match n with
| 0 -> a
| _ -> fib_iter (n - 1) b (a + b) in
fib_iter n 0 1;;

printfn "%d" (fib 10);;


F# code for a maximum value.

let lst = [3;1;4;1;5;9;2];;

let rec fmax l x =
match l with
| [] -> x
| lh::lt ->
fmax lt
(if x > lh then x
else lh);;

printfn "%d" (fmax lst 0);;


I feel that the expression of F# is more powerful than Scheme.