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
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
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
-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With