4
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?

Dickson
  • 43
  • 1
  • 3

1 Answers1

4

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.

pad
  • 41,040
  • 7
  • 92
  • 166
  • @Dickson: Or even shorter: ``fun flat xs = List.foldr op@ [] xs``. But in fact, the standard library already provides this function under the name ``List.concat``. – Andreas Rossberg Feb 23 '13 at 07:23
  • @AndreasRossberg: Thank you. I updated my answer with your suggestions. – pad Feb 23 '13 at 08:16