fun flat [] = []
| flat (l::ls) = l @ flat ls;
This will flatten a list.
Is there a way to non recursively do the same operation? Perhaps with HOFs?
You could use high-order function List.foldr:
fun flat xs = List.foldr (fn (x, acc) => x @ acc) [] xs
As @Andreas said, the function above can be shortened:
fun flat xs = List.foldr op@ [] xs
Although you would like to implement flat
as an exercise, List.concat in the standard library does exactly the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With