さまざまな言語での階乗アルゴリズム
-
09-06-2019 - |
質問
階乗サブルーチンやプログラムについて、皆さんが思いつくさまざまな方法をすべて見てみたいと思います。誰もがここに来て、新しい言語を学びたいと思っているかどうかを確認してほしいと願っています。
アイデア:
- 手続き的
- 機能的
- オブジェクト指向
- ワンライナー
- 難読化された
- 変わり者
- 不正なコード
- 多言語
基本的に、私はアルゴリズムを記述するさまざまな方法の例と、それらがさまざまな言語でどのように見えるかを知りたいのです。
1 つのエントリにつき 1 つの例に限定してください。特定のスタイル、言語、または 1 つの投稿に適したよく考えられたアイデアを強調したい場合は、回答ごとに複数の例を含めることができます。
唯一の実際の要件は、指定された引数の階乗を、表現されているすべての言語で見つけなければならないことです。
クリエイティブに!
推奨ガイドライン:
# Language Name: Optional Style type - Optional bullet points Code Goes Here Other informational text goes here
適切な書式が設定されていない回答は、場合によっては編集することもあります。
解決
多言語対応:5 つの言語、すべて bignum を使用
そこで、私がよく書く 3 つの言語と、この質問に対する他の回答と今日学んだばかりの 3 つの言語で機能する多言語言語を書きました。これはスタンドアロン プログラムで、非負の整数を含む 1 行を読み取り、その階乗を含む 1 行を出力します。Bignum はすべての言語で使用されるため、計算可能な階乗の最大値はコンピューターのリソースのみに依存します。
- パール:組み込みの bignum パッケージを使用します。一緒に走る
perl FILENAME
. - ハスケル:組み込みの bignum を使用します。一緒に走る
runhugs FILENAME
またはお気に入りのコンパイラの同等のもの。 - C++:bignum サポートには GMP が必要です。g++ でコンパイルするには、次を使用します。
g++ -lgmpxx -lgmp -x c++ FILENAME
適切なライブラリにリンクします。コンパイル後、実行します./a.out
. 。または、お気に入りのコンパイラと同等のものを使用してください。 - ブレインファック:私はいくつかの bignum サポートを書きました この郵便受け. 。使用する ミュラーの古典的な分布, 、でコンパイルします
bf < FILENAME > EXECUTABLE
. 。出力を実行可能ファイルにして実行します。または、お気に入りのディストリビューションを使用します。 - 空白:組み込みの bignum サポートを使用します。一緒に走る
wspace FILENAME
.
編集: ホワイトスペースが 5 番目の言語として追加されました。ちなみに、そうしてください ない コードをラップします <code>
タグ;それは空白を壊します。また、コードは固定幅の方が見栄えがよくなります。
char //# b=0+0{- |0*/; #>>>>,----------[>>>>,-------- #define a/*#--]>>>>++<<<<<<<<[>++++++[<------>-]<-<<< #Perl ><><><> <> <> <<]>>>>[[>>+<<-]>>[<<+>+>-]<-> #C++ --><><> <><><>< > < > < +<[>>>>+<<<-<[-]]>[-] #Haskell >>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>] #Whitespace >>>>[-[>+<-]+>>>>]<<<<[<<<<]<<<<[<<<< #brainf*ck > < ]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>*/ exp; ;//;#+<<<<-]<<<<]>>>>+<<<<<<<[<<<<][.POLYGLOT^5. #include <gmpxx.h>//]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>> #define eval int main()//>+<<<-]>>>[<<<+>>+>-> #include <iostream>//<]<-[>>+<<[-]]<<[<<<<]>>>>[>[>>> #define print std::cout << // > <+<-]>[<<+>+>-]<<[>>> #define z std::cin>>//<< +<<<-]>>>[<<<+>>+>-]<->+++++ #define c/*++++[-<[-[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<<*/ #define abs int $n //>< <]<[>>+<<<<[-]>>[<<+>>-]]>>]< #define uc mpz_class fact(int $n){/*<<<[<<<<]<<<[<< use bignum;sub#<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-] z{$_[0+0]=readline(*STDIN);}sub fact{my($n)=shift;#>> #[<<+>+>-]<->+<[>-<[-]]>[-<<-<<<<[>>+<<-]>>[<<+>+>+*/ uc;if($n==0){return 1;}return $n*fact($n-1); }//;# eval{abs;z($n);print fact($n);print("\n")/*2;};#-]<-> '+<[>-<[-]]>]<<[<<<<]<<<<-[>>+<<-]>>[<<+>+>-]+<[>-+++ -}-- <[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<<+>+>-++ fact 0 = 1 -- ><><><>< > <><>< ]+<[>-<[-]]>]<<[<<+ + fact n=n*fact(n-1){-<<]>>>>[[>>+<<-]>>[<<+>+++>+-} main=do{n<-readLn;print(fact n)}-- +>-]<->+<[>>>>+<<+ {-x<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-] <--.<<<<]+written+by+++A+Rex+++2009+.';#+++x-}--x*/;}
他のヒント
ロルコード:
ごめんなさい、我慢できませんでしたxD
HAI
CAN HAS STDIO?
I HAS A VAR
I HAS A INT
I HAS A CHEEZBURGER
I HAS A FACTORIALNUM
IM IN YR LOOP
UP VAR!!1
TIEMZD INT!![CHEEZBURGER]
UP FACTORIALNUM!!1
IZ VAR BIGGER THAN FACTORIALNUM? GTFO
IM OUTTA YR LOOP
U SEEZ INT
KTHXBYE
これは、より高速なアルゴリズムの 1 つです。 170!. 。それ 失敗する 不可解なことに 170! を超えると、小さな階乗では比較的遅くなりますが、次の階乗では比較的遅くなります。 80 そして 170 多くのアルゴリズムと比較して驚くほど高速です。
curl http://www.google.com/search?q=170!
オンラインインターフェースもあり、 今すぐ試してみましょう!
バグを見つけた場合、または大規模な階乗のより高速な実装を見つけた場合はお知らせください。
編集:
このアルゴリズムは若干遅いですが、170 を超える結果が得られます。
curl http://www58.wolframalpha.com/input/?i=171!
また、それらを他のさまざまな表現に単純化します。
C++:テンプレートのメタプログラミング
古典的な enum ハックを使用します。
template<unsigned int n>
struct factorial {
enum { result = n * factorial<n - 1>::result };
};
template<>
struct factorial<0> {
enum { result = 1 };
};
使用法。
const unsigned int x = factorial<4>::result;
階乗は、テンプレート パラメーター n に基づいてコンパイル時に完全に計算されます。したがって、factorial<4>::result は、コンパイラーが処理を完了すると定数になります。
空白
. . . . . . . . . . . . . . . . . . . . . . . . . .
ここに正しく表示するのは難しかったですが、プレビューからコピーしてみたところ、うまくいきました。番号を入力して Enter キーを押す必要があります。
C# ルックアップ:
実際に計算する必要はありません。ただ調べてください。これを拡張するには、テーブルにさらに 8 つの数値を追加します。64 ビット整数は限界に達します。さらに、BigNum クラスが必要になります。
public static int Factorial(int f)
{
if (f<0 || f>12)
{
throw new ArgumentException("Out of range for integer factorial");
}
int [] fact={1,1,2,6,24,120,720,5040,40320,362880,3628800,
39916800,479001600};
return fact[f];
}
怠け者 K
純粋な関数型プログラミングの悪夢が現実になります。
唯一の 難解なチューリング完全プログラミング言語 それは:
- 純粋に機能的な基盤、コア、ライブラリ -- 実際、完全な API は次のとおりです。 SKI
- いいえ ラムダ 平!
- いいえ 数字 または必要または許可されるリスト
- 明示的な再帰はありませんが、まだ、 再帰を許可します
- シンプルな 無限の遅延ストリームベースの I/O メカニズム
以下に、Factorial コードを括弧内にまとめて示します。
K(SII(S(K(S(S(KS)(S(K(S(KS)))(S(K(S(KK)))(S(K(S(K(S(K(S(K(S(SI(K(S(K(S(S(KS)K)I))
(S(S(KS)K)(SII(S(S(KS)K)I))))))))K))))))(S(K(S(K(S(SI(K(S(K(S(SI(K(S(K(S(S(KS)K)I))
(S(S(KS)K)(SII(S(S(KS)K)I))(S(S(KS)K))(S(SII)I(S(S(KS)K)I))))))))K)))))))
(S(S(KS)K)(K(S(S(KS)K)))))))))(K(S(K(S(S(KS)K)))K))))(SII))II)
特徴:
- 減算や条件はありません
- すべての階乗を出力します (十分に長く待った場合)
- 教会数字の 2 番目のレイヤーを使用して、N 階乗を N! に変換します。アスタリスクの後に改行が続く
- を使用します。 Y コンビネータ 再帰用
理解したい場合のために、Lazier コンパイラで実行する Scheme ソース コードを次に示します。
(lazy-def '(fac input)
'((Y (lambda (f n a) ((lambda (b) ((cons 10) ((b (cons 42)) (f (1+ n) b))))
(* a n)))) 1 1))
(Y、cons、1、10、42、1+、および * の適切な定義について)。
編集:
10 進数の Lazy K 階乗
(10KBの意味不明な内容 そうでなければ貼り付けます)。たとえば、Unix プロンプトでは次のようになります。
$ echo "4" | ./lazy facdec.lazy 24 $ echo "5" | ./lazy facdec.lazy 120
たとえば 5 などの数値を超えるとかなり遅くなります。
コードを含める必要があるため、コードはかなり肥大化します。 独自のプリミティブすべてのライブラリ コード (書かれたコード かすんでいる, 、ラムダ計算インタプリタおよび Haskell で書かれた LC から Lazy K へのコンパイラ)。
XSLT 1.0
入力ファイル、 階乗.xml:
<?xml version="1.0"?>
<?xml-stylesheet href="factorial.xsl" type="text/xsl" ?>
<n>
20
</n>
XSLT ファイル、 階乗.xsl:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" >
<xsl:output method="text"/>
<!-- 0! = 1 -->
<xsl:template match="text()[. = 0]">
1
</xsl:template>
<!-- n! = (n-1)! * n-->
<xsl:template match="text()[. > 0]">
<xsl:variable name="x">
<xsl:apply-templates select="msxsl:node-set( . - 1 )/text()"/>
</xsl:variable>
<xsl:value-of select="$x * ."/>
</xsl:template>
<!-- Calculate n! -->
<xsl:template match="/n">
<xsl:apply-templates select="text()"/>
</xsl:template>
</xsl:stylesheet>
両方のファイルを同じディレクトリに保存して開きます 階乗.xml IEでは。
パイソン:機能的、ワンライナー
factorial = lambda n: reduce(lambda x,y: x*y, range(1, n+1), 1)
注記:
- 大きな整数をサポートします。例:
print factorial(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915\
608941463976156518286253697920827223758251185210916864000000000000000000000000
- それは機能しません n < 0.
APL (風変わり/ワンライナー):
×/⍳X
- ⍳X は、X を整数 1..X の配列に展開します。
- ×/ 配列内のすべての要素を乗算します
または、組み込み演算子を使用します。
!X
ソース: http://www.webber-labs.com/mpl/lectures/ppt-slides/01.ppt
x86-64 アセンブリ:手続き的
これは C から呼び出すことができます (Linux amd64 上の GCC でのみテスト済み)。アセンブリはnasmで組み立てました。
section .text
global factorial
; factorial in x86-64 - n is passed in via RDI register
; takes a 64-bit unsigned integer
; returns a 64-bit unsigned integer in RAX register
; C declaration in GCC:
; extern unsigned long long factorial(unsigned long long n);
factorial:
enter 0,0
; n is placed in rdi by caller
mov rax, 1 ; factorial = 1
mov rcx, 2 ; i = 2
loopstart:
cmp rcx, rdi
ja loopend
mul rcx ; factorial *= i
inc rcx
jmp loopstart
loopend:
leave
ret
Inform 7 で再帰的に
(テキスト アドベンチャーを作成するためのものであるため、COBOL を思い出させます。プロポーショナルフォントは意図的に使用されています):
(n - 数値) の階乗はどの数値であるかを判断するには、次のようにします。
n が 0 の場合は 1 を決定します。
それ以外の場合は、(n マイナス 1) 掛ける n の階乗を決定します。
実際にゲームからこの関数 (「フレーズ」) を呼び出したい場合は、アクションと文法規則を定義する必要があります。
「階乗ゲーム」[これはソースの最初の行でなければなりません]
部屋があります。[少なくとも 1 つは存在する必要があります!]
因数分解は数値に適用するアクションです。
「factorial [数値]」を階乗計算として理解します。
因数分解を実行します。
n を理解された数の階乗とします。
「[n]です」と言います。
C#:リンク
public static int factorial(int n)
{
return (Enumerable.Range(1, n).Aggregate(1, (previous, value) => previous * value));
}
アーラン:末尾再帰的
fac(0) -> 1;
fac(N) when N > 0 -> fac(N, 1).
fac(1, R) -> R;
fac(N, R) -> fac(N - 1, R * N).
ハスケル:
ones = 1 : ones
integers = head ones : zipWith (+) integers (tail ones)
factorials = head integers : zipWith (*) factorials (tail integers)
ブレインファック
+++++
>+<[[->>>>+<<<<]>>>>[-<<<<+>>+>>]<<<<>[->>+<<]<>>>[-<[->>+<<]>>[-<<+<+>>>]<]<[-]><<<-]
マイケル・ライツェンシュタイン著。
基本:古い学校
10 HOME
20 INPUT N
30 LET ANS = 1
40 FOR I = 1 TO N
50 ANS = ANS * I
60 NEXT I
70 PRINT ANS
バッチ (NT):
@echo off
set n=%1
set result=1
for /l %%i in (%n%, -1, 1) do (
set /a result=result * %%i
)
echo %result%
使用法:C:>factorial.bat 15
F#:機能的
簡単に言えば:
let rec fact x =
if x < 0 then failwith "Invalid value."
elif x = 0 then 1
else x * fact (x - 1)
おしゃれになる:
let fact x = [1 .. x] |> List.fold_left ( * ) 1
再帰的プロローグ
fac(0,1).
fac(N,X) :- N1 is N -1, fac(N1, T), X is N * T.
末尾再帰プロローグ
fac(0,N,N).
fac(X,N,T) :- A is N * X, X1 is X - 1, fac(X1,A,T).
fac(N,T) :- fac(N,1,T).
ルビー再帰的
(factorial=Hash.new{|h,k|k*h[k-1]})[1]=1
使用法:
factorial[5]
=> 120
スキーム
簡単な再帰定義は次のとおりです。
(define (factorial x)
(if (= x 0) 1
(* x (factorial (- x 1)))))
Scheme の末尾再帰関数では、一定のスタック領域を使用します。以下は、末尾再帰的なバージョンの階乗です。
(define factorial
(letrec ((fact (lambda (x accum)
(if (= x 0) accum
(fact (- x 1) (* accum x))))))
(lambda (x)
(fact x 1))))
奇妙な例は?ガンマ関数を使ってみてはどうでしょうか。以来、 Gamma n = (n-1)!
.
OCaml:ガンマの使用
let rec gamma z =
let pi = 4.0 *. atan 1.0 in
if z < 0.5 then
pi /. ((sin (pi*.z)) *. (gamma (1.0 -. z)))
else
let consts = [| 0.99999999999980993; 676.5203681218851; -1259.1392167224028;
771.32342877765313; -176.61502916214059; 12.507343278686905;
-0.13857109526572012; 9.9843695780195716e-6; 1.5056327351493116e-7;
|]
in
let z = z -. 1.0 in
let results = Array.fold_right
(fun x y -> x +. y)
(Array.mapi
(fun i x -> if i = 0 then x else x /. (z+.(float i)))
consts
)
0.0
in
let x = z +. (float (Array.length consts)) -. 1.5 in
let final = (sqrt (2.0*.pi)) *.
(x ** (z+.0.5)) *.
(exp (-.x)) *. result
in
final
let factorial_gamma n = int_of_float (gamma (float (n+1)))
新入生 Haskell プログラマー
fac n = if n == 0
then 1
else n * fac (n-1)
2年生のHaskellプログラマー、MIT(新入生として学習したスキーム)
fac = (\(n) ->
(if ((==) n 0)
then 1
else ((*) n (fac ((-) n 1)))))
ジュニアハスケルプログラマー(ピアノプレーヤーの始まり)
fac 0 = 1
fac (n+1) = (n+1) * fac n
別のジュニアHaskellプログラマー(N+Kパターンは「Haskellの嫌な部分」であることを読んで[1]、「Ban n+Kパターン」 - モーブメント[2]に参加しました)
fac 0 = 1
fac n = n * fac (n-1)
シニアハスケルプログラマー(ニクソンブキャナンブッシュに投票 - 「傾く正しい」)
fac n = foldr (*) 1 [1..n]
別のシニアHaskellプログラマー(McGovern Biafra Naderに投票 - 「Leans Left」)
fac n = foldl (*) 1 [1..n]
さらに別のシニアHaskellプログラマー(彼は再び左に戻ってきました!)
-- using foldr to simulate foldl
fac n = foldr (\x g n -> g (x*n)) id [1..n] 1
Haskellプログラマをメモ化する(Ginkgo Bilobaを毎日撮る)
facs = scanl (*) 1 [1..]
fac n = facs !! n
Pentless(Ahem)「ポイントフリー」Haskellプログラマー(オックスフォードで勉強)
fac = foldr (*) 1 . enumFromTo 1
反復的なHaskellプログラマ(元Pascalプログラマー)
fac n = result (for init next done)
where init = (0,1)
next (i,m) = (i+1, m * (i+1))
done (i,_) = i==n
result (_,m) = m
for i n d = until d n i
反復的なワンライナーHaskellプログラマー(元APLおよびCプログラマー)
fac n = snd (until ((>n) . fst) (\(i,m) -> (i+1, i*m)) (1,1))
Haskellプログラマーの蓄積(クイッククライマックスまでの構築)
facAcc a 0 = a
facAcc a n = facAcc (n*a) (n-1)
fac = facAcc 1
継続的なパスハスケルプログラマー(初期にラビットを育ててからニュージャージーに移動しました)
facCps k 0 = k 1
facCps k n = facCps (k . (n *)) (n-1)
fac = facCps id
ボーイスカウトハスケルプログラマー(結び目が好きな。常に「re敬の念」、彼は最も固定点の教会に属しています[8])
y f = f (y f)
fac = y (\f n -> if (n==0) then 1 else n * f (n-1))
組み合わせHaskellプログラマー(難読化ではないにしても、変数をEschews変数。このカリー化はすべて単なる段階にすぎませんが、妨げになることはめったにありません)
s f g x = f x (g x)
k x y = x
b f g x = f (g x)
c f g x = f x g
y f = f (y f)
cond p f g x = if p x then f x else g x
fac = y (b (cond ((==) 0) (k 1)) (b (s (*)) (c b pred)))
リストエンコードHaskellプログラマー(単位でカウントすることを好む)
arb = () -- "undefined" is also a good RHS, as is "arb" :)
listenc n = replicate n arb
listprj f = length . f . listenc
listprod xs ys = [ i (x,y) | x<-xs, y<-ys ]
where i _ = arb
facl [] = listenc 1
facl n@(_:pred) = listprod n (facl pred)
fac = listprj facl
通訳Haskellプログラマー(彼が嫌いな「言語に会ったことはない」)
-- a dynamically-typed term language
data Term = Occ Var
| Use Prim
| Lit Integer
| App Term Term
| Abs Var Term
| Rec Var Term
type Var = String
type Prim = String
-- a domain of values, including functions
data Value = Num Integer
| Bool Bool
| Fun (Value -> Value)
instance Show Value where
show (Num n) = show n
show (Bool b) = show b
show (Fun _) = ""
prjFun (Fun f) = f
prjFun _ = error "bad function value"
prjNum (Num n) = n
prjNum _ = error "bad numeric value"
prjBool (Bool b) = b
prjBool _ = error "bad boolean value"
binOp inj f = Fun (\i -> (Fun (\j -> inj (f (prjNum i) (prjNum j)))))
-- environments mapping variables to values
type Env = [(Var, Value)]
getval x env = case lookup x env of
Just v -> v
Nothing -> error ("no value for " ++ x)
-- an environment-based evaluation function
eval env (Occ x) = getval x env
eval env (Use c) = getval c prims
eval env (Lit k) = Num k
eval env (App m n) = prjFun (eval env m) (eval env n)
eval env (Abs x m) = Fun (\v -> eval ((x,v) : env) m)
eval env (Rec x m) = f where f = eval ((x,f) : env) m
-- a (fixed) "environment" of language primitives
times = binOp Num (*)
minus = binOp Num (-)
equal = binOp Bool (==)
cond = Fun (\b -> Fun (\x -> Fun (\y -> if (prjBool b) then x else y)))
prims = [ ("*", times), ("-", minus), ("==", equal), ("if", cond) ]
-- a term representing factorial and a "wrapper" for evaluation
facTerm = Rec "f" (Abs "n"
(App (App (App (Use "if")
(App (App (Use "==") (Occ "n")) (Lit 0))) (Lit 1))
(App (App (Use "*") (Occ "n"))
(App (Occ "f")
(App (App (Use "-") (Occ "n")) (Lit 1))))))
fac n = prjNum (eval [] (App facTerm (Lit n)))
静的Haskellプログラマー(彼はクラスでそれをしています、彼はそのFundep Jonesを持っています!Thomas Hallgren の「関数的依存関係の楽しみ」[7] の後)
-- static Peano constructors and numerals
data Zero
data Succ n
type One = Succ Zero
type Two = Succ One
type Three = Succ Two
type Four = Succ Three
-- dynamic representatives for static Peanos
zero = undefined :: Zero
one = undefined :: One
two = undefined :: Two
three = undefined :: Three
four = undefined :: Four
-- addition, a la Prolog
class Add a b c | a b -> c where
add :: a -> b -> c
instance Add Zero b b
instance Add a b c => Add (Succ a) b (Succ c)
-- multiplication, a la Prolog
class Mul a b c | a b -> c where
mul :: a -> b -> c
instance Mul Zero b Zero
instance (Mul a b c, Add b c d) => Mul (Succ a) b d
-- factorial, a la Prolog
class Fac a b | a -> b where
fac :: a -> b
instance Fac Zero One
instance (Fac n k, Mul (Succ n) k m) => Fac (Succ n) m
-- try, for "instance" (sorry):
--
-- :t fac four
卒業生のHaskellプログラマーを開始する(大学院教育は、たとえば、ハードウェアベースの整数の効率性についての懸念事項から解放する傾向があります)
-- the natural numbers, a la Peano
data Nat = Zero | Succ Nat
-- iteration and some applications
iter z s Zero = z
iter z s (Succ n) = s (iter z s n)
plus n = iter n Succ
mult n = iter Zero (plus n)
-- primitive recursion
primrec z s Zero = z
primrec z s (Succ n) = s n (primrec z s n)
-- two versions of factorial
fac = snd . iter (one, one) (\(a,b) -> (Succ a, mult a b))
fac' = primrec one (mult . Succ)
-- for convenience and testing (try e.g. "fac five")
int = iter 0 (1+)
instance Show Nat where
show = show . int
(zero : one : two : three : four : five : _) = iterate Succ Zero
折り紙のhaskellプログラマー(常に「基本的な鳥の折りたたみ」から始めます)
-- (curried, list) fold and an application
fold c n [] = n
fold c n (x:xs) = c x (fold c n xs)
prod = fold (*) 1
-- (curried, boolean-based, list) unfold and an application
unfold p f g x =
if p x
then []
else f x : unfold p f g (g x)
downfrom = unfold (==0) id pred
-- hylomorphisms, as-is or "unfolded" (ouch! sorry ...)
refold c n p f g = fold c n . unfold p f g
refold' c n p f g x =
if p x
then n
else c (f x) (refold' c n p f g (g x))
-- several versions of factorial, all (extensionally) equivalent
fac = prod . downfrom
fac' = refold (*) 1 (==0) id pred
fac'' = refold' (*) 1 (==0) id pred
カートシアンに含むHaskellプログラマー(ギリシャ料理を好み、スパイシーなインドのものを避けます。Lex Augusteijn の「Sorting Morphisms」[3] からインスピレーションを得た)
-- (product-based, list) catamorphisms and an application
cata (n,c) [] = n
cata (n,c) (x:xs) = c (x, cata (n,c) xs)
mult = uncurry (*)
prod = cata (1, mult)
-- (co-product-based, list) anamorphisms and an application
ana f = either (const []) (cons . pair (id, ana f)) . f
cons = uncurry (:)
downfrom = ana uncount
uncount 0 = Left ()
uncount n = Right (n, n-1)
-- two variations on list hylomorphisms
hylo f g = cata g . ana f
hylo' f (n,c) = either (const n) (c . pair (id, hylo' f (c,n))) . f
pair (f,g) (x,y) = (f x, g y)
-- several versions of factorial, all (extensionally) equivalent
fac = prod . downfrom
fac' = hylo uncount (1, mult)
fac'' = hylo' uncount (1, mult)
博士号Haskellプログラマー(非常に多くのバナナを食べたので、彼の目は盗まれました、今では彼は新しいレンズが必要です!)
-- explicit type recursion based on functors
newtype Mu f = Mu (f (Mu f)) deriving Show
in x = Mu x
out (Mu x) = x
-- cata- and ana-morphisms, now for *arbitrary* (regular) base functors
cata phi = phi . fmap (cata phi) . out
ana psi = in . fmap (ana psi) . psi
-- base functor and data type for natural numbers,
-- using a curried elimination operator
data N b = Zero | Succ b deriving Show
instance Functor N where
fmap f = nelim Zero (Succ . f)
nelim z s Zero = z
nelim z s (Succ n) = s n
type Nat = Mu N
-- conversion to internal numbers, conveniences and applications
int = cata (nelim 0 (1+))
instance Show Nat where
show = show . int
zero = in Zero
suck = in . Succ -- pardon my "French" (Prelude conflict)
plus n = cata (nelim n suck )
mult n = cata (nelim zero (plus n))
-- base functor and data type for lists
data L a b = Nil | Cons a b deriving Show
instance Functor (L a) where
fmap f = lelim Nil (\a b -> Cons a (f b))
lelim n c Nil = n
lelim n c (Cons a b) = c a b
type List a = Mu (L a)
-- conversion to internal lists, conveniences and applications
list = cata (lelim [] (:))
instance Show a => Show (List a) where
show = show . list
prod = cata (lelim (suck zero) mult)
upto = ana (nelim Nil (diag (Cons . suck)) . out)
diag f x = f x x
fac = prod . upto
ポスドックハスケルプログラマー(ウスタル、ベネ、パルドの「コモナドからの再帰スキーム」[4])
-- explicit type recursion with functors and catamorphisms
newtype Mu f = In (f (Mu f))
unIn (In x) = x
cata phi = phi . fmap (cata phi) . unIn
-- base functor and data type for natural numbers,
-- using locally-defined "eliminators"
data N c = Z | S c
instance Functor N where
fmap g Z = Z
fmap g (S x) = S (g x)
type Nat = Mu N
zero = In Z
suck n = In (S n)
add m = cata phi where
phi Z = m
phi (S f) = suck f
mult m = cata phi where
phi Z = zero
phi (S f) = add m f
-- explicit products and their functorial action
data Prod e c = Pair c e
outl (Pair x y) = x
outr (Pair x y) = y
fork f g x = Pair (f x) (g x)
instance Functor (Prod e) where
fmap g = fork (g . outl) outr
-- comonads, the categorical "opposite" of monads
class Functor n => Comonad n where
extr :: n a -> a
dupl :: n a -> n (n a)
instance Comonad (Prod e) where
extr = outl
dupl = fork id outr
-- generalized catamorphisms, zygomorphisms and paramorphisms
gcata :: (Functor f, Comonad n) =>
(forall a. f (n a) -> n (f a))
-> (f (n c) -> c) -> Mu f -> c
gcata dist phi = extr . cata (fmap phi . dist . fmap dupl)
zygo chi = gcata (fork (fmap outl) (chi . fmap outr))
para :: Functor f => (f (Prod (Mu f) c) -> c) -> Mu f -> c
para = zygo In
-- factorial, the *hard* way!
fac = para phi where
phi Z = suck zero
phi (S (Pair f n)) = mult f (suck n)
-- for convenience and testing
int = cata phi where
phi Z = 0
phi (S f) = 1 + f
instance Show (Mu N) where
show = show . int
終身教授(新入生にハスケルを教える)
fac n = product [1..n]
D テンプレート:機能的
template factorial(int n : 1)
{
const factorial = 1;
}
template factorial(int n)
{
const factorial =
n * factorial!(n-1);
}
または
template factorial(int n)
{
static if(n == 1)
const factorial = 1;
else
const factorial =
n * factorial!(n-1);
}
このように使用されます:
factorial!(5)
Java 1.6:再帰的、メモ化 (後続の呼び出し用)
private static Map<BigInteger, BigInteger> _results = new HashMap()
public static BigInteger factorial(BigInteger n){
if (0 >= n.compareTo(BigInteger.ONE))
return BigInteger.ONE.max(n);
if (_results.containsKey(n))
return _results.get(n);
BigInteger result = factorial(n.subtract(BigInteger.ONE)).multiply(n);
_results.put(n, result);
return result;
}
パワーシェル
function factorial( [int] $n )
{
$result = 1;
if ( $n -gt 1 )
{
$result = $n * ( factorial ( $n - 1 ) )
}
$result
}
ワンライナーは次のとおりです。
$n..1 | % {$result = 1}{$result *= $_}{$result}
バッシュ:再帰的
bash および再帰的ですが、新しいプロセスで各反復を処理するという追加の利点があります。計算できる最大値は、オーバーフローするまでの !20 ですが、答えを気にせず、システムが倒れてもよい場合は、大きな数値に対しても実行できます ;)
#!/bin/bash
echo $(($1 * `( [[ $1 -gt 1 ]] && ./$0 $(($1 - 1)) ) || echo 1`));