Dickson
Dickson

Reputation: 43

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?

Upvotes: 4

Views: 3299

Answers (1)

pad
pad

Reputation: 41290

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.

Upvotes: 4

Related Questions