これはおそらく最も簡単なものです:
Prelude> let odometer a = sequence a
Prelude> odometer [["a1","a2","a3"],["b1","b2"],["c1","c2","c3","c4"]]
[["a1","b1","c1"],["a1","b1","c2"],["a1","b1","c3"],["a1","b1","c4"],["a1","b2","c1"],
["a1","b2","c2"],["a1","b2","c3"],["a1","b2","c4"],["a2","b1","c1"],["a2","b1","c2"],
["a2","b1","c3"],["a2","b1","c4"],["a2","b2","c1"],["a2","b2","c2"],["a2","b2","c3"],
["a2","b2","c4"],["a3","b1","c1"],["a3","b1","c2"],["a3","b1","c3"],["a3","b1","c4"],
["a3","b2","c1"],["a3","b2","c2"],["a3","b2","c3"],["a3","b2","c4"]]
Prelude>
sequence
モナドを扱う関数です。Haskell を使いたい場合は、モナドを理解する必要があるので、今すぐ始めたほうがよいかもしれません。
強力なモナドをまだ生活に取り入れる準備ができていない場合は、より平凡なバージョンを次に示します。
Prelude> :{
Prelude| let odometer (xs:yys) = [x:ys | x<-xs, ys<-odometer yys]
Prelude| odometer [] = [[]]
Prelude| :}
Prelude> odometer [["a1","a2","a3"],["b1","b2"],["c1","c2","c3","c4"]]
[["a1","b1","c1"],["a1","b1","c2"],["a1","b1","c3"],["a1","b1","c4"],["a1","b2","c1"],
["a1","b2","c2"],["a1","b2","c3"],["a1","b2","c4"],["a2","b1","c1"],["a2","b1","c2"],
["a2","b1","c3"],["a2","b1","c4"],["a2","b2","c1"],["a2","b2","c2"],["a2","b2","c3"],
["a2","b2","c4"],["a3","b1","c1"],["a3","b1","c2"],["a3","b1","c3"],["a3","b1","c4"],
["a3","b2","c1"],["a3","b2","c2"],["a3","b2","c3"],["a3","b2","c4"]]
Prelude>
それは缶に書かれていることを正確に行います:
- 走行距離計ホイールのリストが与えられた場合
(xs:yys)
- 可能なすべての読み取り値のリストは、xとysの可能なすべての組み合わせのリストです。
= [ x:ys
- そのような
|
- xは、最初のホイールのすべての可能な位置のリストから取得されます
x<-xs
- と
,
- ysは、残りの車輪 (つまり、最初の車輪以外のすべて) から作成された走行距離計のすべての可能な読み取り値のリストから取得されます
ys<-odometer yys]
。
- 走行距離計に車輪がない場合
[]
- 空である可能性のある読み取りは 1 つだけです。
= [[]]