関数は整数要素の順序付きリストを取得し、元のリスト内の隣接する要素のすべての組み合わせを返す必要があります。
[1,2,3]
は [1,2,3]、[1]、[1,2]、[2]、[2,3]、[
。
3]]
1
と 3
は元のリストに隣接していないので、
[1,3]
は含めないでください。
ベストアンサー
inits
と tails
が Prelude
に見つからないという事実とは別に、あなたの関数を以下のように定義することができます:
yourFunction :: [a] -> [[a]]
yourFunction = filter (not . null) . concat . map inits . tails
これは、ステップバイステップで行われます。
-
tails
gives all versions of a list with zero or
more starting elements removed:tails [1,2,3] ==
[[1,2,3],[2,3],[3],[]] -
map inits
appliesinits
to every list
given bytails
, and does exactly the opposite: it
gives all versions of a list with zero or more ending elements
removed:inits [1,2,3] == [[],[1],[1,2],[1,2,3]]
- I hope you already know
concat
: it applies
(++)
where you see(:)
in a list:
concat [[1,2],[3],[],[4]] == [1,2,3,4]
. You need this,
because aftermap inits . tails
, you end up with a
list of lists of lists, while you want a list of lists. -
filter (not . null)
removes the empty lists from
the result. There will be more than one (unless you use the
function on the empty list).
また、 concatの代わりに
concatMap inits を使用することもできます。 map
inits 。これはまったく同じことです。それは通常、より良いパフォーマンスを発揮します。
編集:これを Prelude
だけで定義することができます:
yourFunction = concatMap inits . tails
where inits = takeWhile (not . null) . iterate init
tails = takeWhile (not . null) . iterate tail