Friday, December 29, 2006

Ninety-nine Lisp Problem #p04,#p05


P04 (*) Find the number of elements of a list.

ทำได้ 2 แบบคือ
1. ใช้ recursive ธรรมดา
2. ใช้ tail recursive

clisp
(defun len (lst)
(if (null lst)
0
(1+ (len (cdr lst)))))

(defun len-2 (lst &optional (cnt 0))
(if (null lst)
cnt
(len-2 (cdr lst) (1+ cnt))))


haskell
len :: [a] -> Int
len ([]) = 0
len (_:xs) = 1 + len xs


len_2 :: [a] -> Int
len_2 (xs) = len_helper xs 0
where
len_helper ([]) n = n
len_helper (_:xs) n = len_helper xs (n + 1)


erlang
-module(p04).
-export([len/1,len_2/1]).

len([]) ->
0;
len([_|XS]) ->
1 + len(XS).


len_2(L) ->
len_iter(L,0).

len_iter([],N) ->
N;
len_iter([_|XS],N) ->
len_iter(XS,N+1).


P05 (*) Reverse a list.


implement ทั้งหมดแบบ tail-recursive

clisp
(defun rev (lst &optional (tmp '()))
(if (null lst)
tmp
(rev (cdr lst) (cons (first lst) tmp))))


haskell
inv :: [a] -> [a]
inv l = invx l []
where
invx [] y = y
invx (x:xs) y = invx xs (x : y)

ดูยาว, แต่ถ้าไปดู implement ของ hugs เขาจะเขียนแค่นี้
reverse   :: [a] -> [a]
reverse = foldl (flip (:)) []


erlang
-module(p05).
-export([rev/1]).

rev(X) ->
rev(X,[]).

rev([], L) ->
L;
rev([H|T], L) ->
rev(T, [H|L]).

Related link from Roti

No comments: