Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to List in SML

Tags:

sml

How do i convert an array type to a list type in sml. I have searched the list and array structure functions but have not found one that does this (there is a list to array function though).

Description of List structure: http://sml-family.org/Basis/list.html

Description of Array structure: http://sml-family.org/Basis/array.html

like image 832
abden003 Avatar asked Dec 24 '22 19:12

abden003


2 Answers

While there isn't a built in direct conversion function, you could use Array.foldr to quite easily construct a corresponding list:

fun arrayToList arr = Array.foldr (op ::) [] arr

Example:

- val arr = Array.fromList [6, 3, 5, 7];
val arr = [|6,3,5,7|] : int array

- val ls = arrayToList arr;
val ls = [6,3,5,7] : int list
like image 196
Sebastian Paaske Tørholm Avatar answered Jan 25 '23 23:01

Sebastian Paaske Tørholm


There doesn't seem to be a built-in List.fromArray or Array.toList. It looks like the easiest way to define it would be

List.tabulate(Array.length(arr), fn i => Array.sub(arr, i))

So...

Standard ML of New Jersey v110.76 [built: Thu Feb 19 00:37:13 2015]
- val arr = Array.fromList([1, 2, 3, 4, 5]) ;;
[autoloading]
[library $SMLNJ-BASIS/basis.cm is stable]
[autoloading done]
val arr = [|1,2,3,4,5|] : int array

- fun listFromArray arr = List.tabulate(Array.length(arr), fn i => Array.sub(arr, i)) ;;
[autoloading]
[autoloading done]
val listFromArray = fn : 'a array -> 'a list

- listFromArray(arr) ;;
val it = [1,2,3,4,5] : int list

- 
like image 43
Inaimathi Avatar answered Jan 25 '23 23:01

Inaimathi