こんにちは、Ocaml でリストをフラット化しようとしています。私は初心者なので、私の間違いがばかげている場合はご容赦ください
たとえば、入力が [[1];[2;3];[4]] の場合、[1;2;3;4] になります。
私が使用しようとしているアイデアは次のとおりです 右からリストを反復処理します (fold_right を使用) with accumaltor = [] 擬似コードは次のとおりです
func flatten(list, accumalator)
For each item from right to left in list
If Item is a scalar then n :: accumalator
Else fi Item is a list of form head :: tail then
head :: flatten (tail, accumalator).
理論的にはアルゴリズムは正しいと思いますが、そうでない場合はお知らせください。
次に、このアルゴリズムを実装するための OCaml コードに進みます
let rec flatten acc x =
match x with
n -> n :: acc
| [x] -> x :: acc
| head :: remainder ->
head :: ( my_flat acc remainder )
and my_flat = List.fold_right flatten
;;
my_flat [] [[1];[2;3];[4]]
私が得るエラーは次のエラーです: This expression has type 'a but an expression was expected of type 'a list
エラーは、match ステートメントの最後のパターンで head :: ( my_flat acc Removal ) を読み取る行で発生します。
どんな助けでも大歓迎です。