回答編集履歴

1

Lists.fold_leftを使った例を追記しました

2021/05/18 13:43

投稿

tatsuya6502
tatsuya6502

スコア2035

test CHANGED
@@ -127,3 +127,63 @@
127
127
  [("melon", 3); ("grape", 3); ("grape", 1); ("banana", 3); ("apple", 2); ("apple", 1)]
128
128
 
129
129
  ```
130
+
131
+
132
+
133
+ ---
134
+
135
+
136
+
137
+ **追記**
138
+
139
+
140
+
141
+ コメント欄で`Lists.fold_left`を使わない方法で完成したとの連絡を受けました。完成してよかったです!
142
+
143
+
144
+
145
+ 参考までに`Lists.fold_left`を使った方法を追記します。
146
+
147
+
148
+
149
+ ```ocaml
150
+
151
+ # let l = [("apple", 1); ("grape", 1) ; ("apple", 2); ("grape", 3); ("melon", 3); ("banana", 3)];;
152
+
153
+ val l : (string * int) list =
154
+
155
+ [("apple", 1); ("grape", 1); ("apple", 2); ("grape", 3); ("melon", 3); ("banana", 3)]
156
+
157
+
158
+
159
+ # let l' = List.sort (fun x y -> ~- (compare x y)) l;;
160
+
161
+ val l' : (string * int) list =
162
+
163
+ [("melon", 3); ("grape", 3); ("grape", 1); ("banana", 3); ("apple", 2); ("apple", 1)]
164
+
165
+
166
+
167
+ # let f = fun acc item ->
168
+
169
+ match (item, acc) with
170
+
171
+ (* 第一項が一緒なのでまとめる *)
172
+
173
+ | ((x, y), (x', ys)::rest) when x = x' -> (x, y::ys)::rest
174
+
175
+ (* 第一項が異なる。(accが[]のときも含む) *)
176
+
177
+ | ((x, y), _) -> (x, [y])::acc;;
178
+
179
+ val f : ('a * 'b list) list -> 'a * 'b -> ('a * 'b list) list = <fun>
180
+
181
+
182
+
183
+ # List.fold_left f [] l';;
184
+
185
+ - : (string * int list) list =
186
+
187
+ [("apple", [1; 2]); ("banana", [3]); ("grape", [1; 3]); ("melon", [3])]
188
+
189
+ ```