print/return cons version of a list in SML

50 Views Asked by At

I want smlnj to return a list in its cons form when I input a list in the regular list notation. Is there a way to get smlnj to do this for me?

Here is an example:

input: [1,2,3]
output: 1::2::3::[]

I want to use this to understand how more complicated int list lists are stored internally through some examples.

2

There are 2 best solutions below

0
Sam Westrick On

You can get pretty close by creating your own list type. Here we write empty instead of [], and ::: instead of ::, but otherwise it's identical to normal lists.

datatype 'a mylist = empty | ::: of 'a * 'a mylist
infixr 5 :::
fun mylist (xs: 'a list) =
  case xs of
    [] => empty
  | x :: xs' => x ::: mylist xs'

SML/NJ will show values of this type without any syntax sugar.

- mylist [1,2,3];
val it = 1 ::: 2 ::: 3 ::: empty : int mylist
0
Chris On

You could extrapolate out the function to convert elements to strings and get a a function to convert a 'a list into a string.

fun listToString(_, []) = "[]"
  | listToString(f, x::xs) = 
      f x ^ " :: " ^ listToString(f, xs);

Then:

listToString(Int.toString, [1,2,3]);
(* "1 :: 2 :: 3 :: []" *)

listToString(
  fn x => "(" ^ listToString(Int.toString, x) ^ ")", 
  [[1, 2], [3, 4]]
); 
(* "(1 :: 2 :: []) :: (3 :: 4 :: []) :: []" *)