I have this assignment:
Consider a list where every element is a nested list of length 2. The first element of each nested list is either a 0 or a 1. The second element of each nested list is some integer. An example input in Scheme is written below.
'((0 1) (1 2) (1 3) (0 4) (0 3))For the purposes of this question, let’s call the first element of each nested list the key and the second element of the nested lists the value. Now consider a function,
count_by_cat, that takes such a list as input and yields a two-element list where
- the first element is the sum of the values of all nested lists with 0 as the key, and
- the second element is the sum of the values of all nested lists with 1 as the key
Implement
count_by_catin
- (a) Racket, and
- (b) ML.
It might be helpful to create helper functions. Also do not forget about
mapandfilter(filteris not a built-in in ML).
I'm new to Racket and ML. I'm stuck at using accessing lists and stuff in Racket. Some help with ML would also be great.
The hint about
mapandfilteris a bit of a red herring (As well as being wrong about them not being in ML languages); a helper function is very useful, but it's a fold you want, which basically calls a function with the current element of a list and an accumulator value, and uses what it returns as the accumulator for the next element and ultimately the return value of the entire fold.For example, in ocaml, using a fold to sum a list of integers:
(
(+)is the function version of the infix operator+).Or your problem in Racket, using the
for/foldcomprehension, and returning two values instead of a two-element list, which is more idiomatic in Racket and Scheme (In ocaml and presumably Standard ML, you'd return a two-element tuple instead of a list, and take a list of tuples).You could also use
foldl, butfor/foldis often easier to use, especially when working with multiple values or other non-trivial cases.