Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

sml

smlnj

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?

like image 390
Dickson Avatar asked Oct 18 '25 15:10

Dickson


1 Answers

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.

like image 136
pad Avatar answered Oct 21 '25 20:10

pad