Haskell for C/C++ 階乗

Powered by dKingyo / 人口を増やす / 就職口を増やす | 256倍使うための本 | VB2005 | 明快入門 | Linux | CSS

C言語

int fact(int x){
 if(0==x) return 1;
 else return x * fact(x-1);
}

Haskell

fact :: Int -> Int -- fact は Intの引数をとってIntを返す関数	  
fact x = 
  if x==0 then 1
  else x * fact (x-1)

WinHugsでの処理結果


C言語のテストプログラム

#include <stdio.h>

int fact(int x){
 if(0==x) return 1;
 else return x * fact(x-1);
}


int main(){
 int i,r;
 /* 0〜6までの階乗を試す */
 for(i=0;i<6;i++){
  r = fact(i);
  printf("%d\n",r);
 }
 return 0;
}

Haskellのテストプログラム

--階乗関数を定義
fact :: Int -> Int   
fact n = if n==0 
  then 1
  else n * fact (n-1)

--[]を使ってfactが沢山の引数を扱えるようにする。
fl :: [Int] -> [Int]
fl (x:xs) = fact x : fl xs
fl[] = []

main = do print $ fl[0,1,2,3,4,5]

*1

処理結果


1
1
2
6
24
120

*1:[0,1,2,3,4,5]が気にくわない。もっとスマートな書き方があるはずだ。C言語でのforで配列を初期化するような形の・・・