Search code examples
listsmlsmlnj

How to flatten a list non-recursively in sml/nj?


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?


Solution

  • 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.