Search code examples
listfunctional-programmingsmlsmlnj

Adding items to list SML


I'm very new to SML and I'm trying to add some items to a list

fun foo(inFile : string, outFile : string) = let
val file = TextIO.openIn inFile
val outStream = TextIO.openOut outFile
val contents = TextIO.inputAll file
val lines = String.tokens (fn c => c = #"\n") contents
val lines' = List.map splitFirstSpace lines
fun helper1(lis : string list) =
    case lis of
          [] => ( TextIO.closeIn file; TextIO.closeOut outStream)
      |  c::lis => ( TextIO.output(outStream, c);
    helper1(lis))
fun helper(lis : (string * string) list, stack : string list) =
    case lis of
          [] => stack
      |  c::lis => ( act(#1 c, #2 c)::stack;
    helper(lis, stack))
val x = helper(lines', [])
in
helper1(x)
end;

I'm getting a blank output file whenever I run the code and I'm having trouble figuring out why but I do know that the helper function is getting the proper values from the "act" function because I tested it by using print(action(...))

Thanks


Solution

  • The problem is with this part:

    ( act(#1 c, #2 c)::stack; helper(lis, stack) )
    

    This is creating a new list and then immediately throwing it away before performing the recursive call. What you want to do instead is

    helper(lis, act(#1 c, #2 c)::stack)
    

    Additional hint: both your helper functions can be replaced by simple uses of List.app and List.foldl.

    Edit: Further hint: In fact, you can write that as just

    helper(lis, act(c)::stack)
    

    because a function with "two arguments" is simply a function taking a pair.