Feb 29, 2008

FizzBuzz Object (C#)


class Program
{
static void Main(string[] args)
{
var fizzbuzz = new
{
Case = new[] {
new {
Cond = new Func<int, bool>(n => true),
Proc = new Func<int, string>(n => null)
}
},
Convert = new Func<int, string>(n => null),
Get = new Func<int, int, IEnumerable<string>>((start, count) => null)
};

fizzbuzz = new
{
Case = new[]
{
new {
Cond = new Func<int, bool>(n => n % 15 == 0),
Proc = new Func<int, string>(n => "FizzBuzz")
},
new {
Cond = new Func<int, bool>(n => n % 3 == 0),
Proc = new Func<int, string>(n => "Fizz")
},
new {
Cond = new Func<int, bool>(n => n % 5 == 0),
Proc = new Func<int, string>(n => "Buzz")
},
new {
Cond = new Func<int, bool>(n => true),
Proc = new Func<int, string>(n => n.ToString())
}
},
Convert = new Func<int, string>(n => fizzbuzz.Case.Where(c => c.Cond(n)).First().Proc(n)),
Get = new Func<int, int, IEnumerable<string>>((start, count) => Enumerable.Range(start, count).Select(n => fizzbuzz.Convert(n)))
};

foreach (var x in fizzbuzz.Get(1, 100))
{
Console.Write(x + " ");
}

Console.ReadLine();
}
}



  • It's impossible to access fizzbuzz while initializing of fizzbuzz.

  • It's regarded as same type when an anonymous types have same properties.

  • It's impossible to set lambda expression to a property of anonymous type.

  • It's impossible to use yield keyword in anonymous method.

Feb 28, 2008

"Nabeatsu of the World" program.

It becomes "Aho" if multiples of 3 or numbers including 3.

module Enumerable
def aho(&block)
self.map do |a|
if 100 <= a
a.to_s
elsif block.call(a)
a.to_aho
else
a.to_s
end
end
end
end

class Integer
def to_aho
fig1 = [ "", "iiiichi", "niiii", "saaaan", "siiii", "goooo", "rooooku", "siiiichi", "haaaachi", "kyuuuu" ]
fig10 = [ "", "", "ni", "san", "yon", "go", "roku", "nana", "hachi", "kyu" ]

if self < 10
fig1[self]
elsif 10 <= self
fig10[self / 10] + "-ju-" + fig1[self % 10]
else
n.to_s
end
end
end


(1..100).aho{|a| (a % 3 == 0) || a.to_s.include?("3") }.each{|a| printf("%s ", a) }

Feb 27, 2008

How to make an Expression Tree.

I want to make this lambda expression.

Func mean = (x, y) => ((x + y) / 2);

Console.WriteLine(mean(10, 20));


Use Expression class.

ParameterExpression x = Expression.Parameter(typeof(int), "x");
ParameterExpression y = Expression.Parameter(typeof(int), "y");

ConstantExpression two = Expression.Constant(2, typeof(int));

BinaryExpression add = Expression.Add(x, y);
BinaryExpression body = Expression.Divide(add, two);

Expression<Func<int, int, int>> meanExp =
Expression.Lambda<Func<int, int, int>>(
body,
new ParameterExpression[] { x, y });
Func<int, int, int> mean = meanExp.Compile();

Console.WriteLine(meanExp);
Console.WriteLine(mean(10, 20));

Feb 26, 2008

Lazy Evaluation of Haskell.

From Exercise 1.5 of SICP.

What the result is this Scheme code.

(define (p) (p))

(define (test x y)
(if (= x 0)
0
y))

(test 0 (p))

It's an infinite loop.

The case of Haskell.

p = p

test x y = case x of
0 -> 0
_ -> y

test 0 p

The result is zero.
This is Lazy Evaluation of Haskell.

Feb 25, 2008

Square Roots by Newton's Method.

Square Roots by Newton's Method.

(define (sqrt x)
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001))
(define (improve guess)
(average guess (/ x guess)))
(define (sqrt-iter guess)
(if (good-enough? guess)
guess
(sqrt-iter (improve guess))))
(sqrt-iter 1.0))

"x" is a free variable in the internal definitions.It gets its value from the argument with which the enclosing procedure sqrt is called.This dicipline is called "lexical scoping".

Feb 24, 2008

The SDK of iPod touch.

When I get the SDK of iPod touch?
Which programming language can I use?

Feb 23, 2008

"yield" in JavaScript 1.7

It's possible to use "yield" keyword in JavaScript 1.7.
It requires to specify the version (1.7).

<body>
<script type="text/javascript; version=1.7">

var i = 0;
var gen = (function() { while(1) { yield i++; } })();
alert(gen.next()); // 0
alert(gen.next()); // 1
alert(gen.next()); // 2

</script>
</body>

Feb 22, 2008

Quick Sort (Haskell vs C#)

A function for Quick Sort.

C#

static int[] QuickSort(int[] a, int c)
{
if (a.Length == 0) return a;
if (c == 0) return a;

int p = a[0];

int l = 0;
int h = 0;
int[] lo = new int[a.Length];
int[] hi = new int[a.Length];

for (int i = 1; i < c; i++)
{
if (a[i] < p)
{
lo[l++] = a[i];
}
else
{
hi[h++] = a[i];
}
}

lo = QuickSort(lo, l);
lo[l++] = p;
hi = QuickSort(hi, h);
for (int i = 0; l < lo.Length; i++)
{
lo[l++] = hi[i];
}

return lo;
}

Too difficult.


Haskell

qsort [] = []
qsort (p:xs) = qsort lt ++ [p] ++ qsort gteq
where
lt = [x | x <- xs, x < p]
gteq = [x | x <- xs, x >= p]

Very simple.


C# with Enumerable

static IEnumerable QuickSort(IEnumerable a)
{
if (a.Count() == 0) return a;

int p = a.First();
var xs = a.Skip(1);
var lo = xs.Where(y => y < p);
var hi = xs.Where(y => y >= p);

return QuickSort(lo).Concat(new[] { p }).Concat(QuickSort(hi));
}

This code get close to Haskell's one.

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.

Feb 14, 2008

Lambda Expression for maximum value.

When I don't use Lambda Expression.

int[] list = { 3, 1, 4, 1, 5, 9, 2 };

int max = 0;

for (int i = 0; i < list.Length; i++)
{
if (max < list[i])
{
max = list[i];
}
}

Console.WriteLine(max);


When I use Lambda Expression.

int[] list = { 3, 1, 4, 1, 5, 9, 2 };

Func fmax = null;
fmax = (l, x, i) => (i == l.Length) ? x : fmax(l, (x > l[i]) ? x : l[i], i + 1);

Console.WriteLine(fmax(list, 0, 0));


I can write functional program with Lambda Expression.

Feb 13, 2008

C# derives from...

C# is C++++.
By the way, the code name of C# was COOL (C like Object Oriented Language).

Feb 12, 2008

(SICP) 1 Building Abstractions with Procedures

I'm trying to read "Structure and Interpretation of Computer Programs" (SICP).
Today, I read "1 Building Abstractions with Procedures".
It's be summarized as follows.
Programming in Lisp is great fun.

Feb 11, 2008

Foreword of SICP.

I'm trying to read "Structure and Interpretation of Computer Programs" (SICP).
Today, I read "Foreword".
It's described about programming, Lisp and so on.

Feb 10, 2008

The SICP Web Site.

We can read "Structure and Interpretation of Computer Programs" (SICP) on web.

Welcome to the SICP Web Site

I'll try to read it.
But I'm not good at English...

Feb 9, 2008

How to read web pages offline on iPhone/iPod touch.

You can read web pages on iPhone/iPod touch when you are offline.

Read Offline for iPhone/iPod touch

This is a bookmarklet.

It's very convenient to read web pages offline.

Feb 8, 2008

Prototype chain of JavaScrit.

Prototype chain is a inheritance system of JavaScript.
Prototype of sub class is instance of base class.


var Person = function() {};
Person.prototype = {
name : "hoge",
toString : function() {
window.alert(this.name);
}
};

var Programmer = function() {};
Programmer.prototype = new Person();

var shunsuk = new Programmer();
shunsuk.name = "shunsuk";
shunsuk.toString();

Feb 7, 2008

Closure of JavaScript and C#.

A closure is a function that is evaluated in an environment containing one or more bound variables.

JavaScript.

function closure(init) {
var cnt = init;

return function() {
return ++cnt;
}
}

var r = closure(10);

alert(r());
alert(r());
alert(r());



C#.

Func<int, Func<int>> closure = init =>
{
int cnt = init;
return () => ++cnt;
};

var r = closure(10);

Console.WriteLine(r());
Console.WriteLine(r());
Console.WriteLine(r());



Output.

11
12
13

Feb 6, 2008

16GB iPhone and 32GB iPod touch.

Macworld | Apple offers 16GB iPhone, 32GB iPod touch

Apple on Tuesday added new models of the iPhone and iPod touch with more storage capacity. The company is now offering a 16GB version of the iPhone for $499, and a 32GB version of the iPod touch for $499. Both new devices are available immediately.


New iPod touch is applied the software update.
It includes five applications and home customize.

Feb 5, 2008

Scheme program for prime numbers.

I wrote a Scheme program that make a list of prime numbers.


(define (prime)
(define (prime-loop n pr)
(define (p? i p)
(if (= (length p) 0)
#t
(if (= (remainder i (car p)) 0)
#f
(p? i (cdr p)))))
(if (<= n 1000)
(prime-loop (+ n 1)
(if (p? n pr)
(append pr (list n))
pr))
pr))
(prime-loop 2 '()))


You write a faster program if you use Sieve of Eratosthenes.
Sieve of Eratosthenes - Wikipedia, the free encyclopedia

Feb 4, 2008

"prototype" of JavaScript.

I decided to learn "prototype" of JavaScript.
Prototype-base object oriented programming seems to be interesting.

Feb 3, 2008

Lambda calculus.

I'm interested in Lambda calculus.
It's too difficult for me.
But I do the best to understand it.

Feb 2, 2008

Many programming languages for .NET.

Many .NET languages are introduced in this page.

.NET Languages

I have used Ruby for .NET.
I'm interesting in Scheme for .NET.

I want to make Scheme.NET.

Feb 1, 2008

Combination of Ruby and Silverlight.

A Ruby CGI program outputs JavaScript for Silverlight.

http://tech.upper.jp/droptext/word/(a word you like)

Example:
http://tech.upper.jp/droptext/word/Hello,%20world%21