Truncation in ML Part 2

时间:2015-07-28 16:33:40

标签: functional-programming sml

I'm nearly there on truncating a string in ML, but am getting an error about not handling an empty list. Here's my code and the error:

fun getAllButLast([x]) = nil
    | getAllButLast(x::xs) = x::getAllButLast(xs);

fun truncate(myString, 1) = str(hd(explode(myString)))
    | truncate(myString, limit) =
    let
        val x::xs = explode(myString);
    in
        str(x) ^ truncate(implode(getAllButLast(xs)), limit - 1)
    end;

I load the file and call truncate("heythere", 5), which should give me "heyth". Instead, I get this error:

uncaught exception Empty
  raised at: smlnj/init/pervasive.sml:209.19-209.24

This is pretty surprising since, as long as I input a limit number (the second parameter) that's $\ge$ 1, the string (or list of characters representing the string) should never be empty.

Any idea what's going on?

Thanks, bclayman

1 个答案:

答案 0 :(得分:2)

You are dropping two characters at every recursive step: the first one (x) and the last one. So the length of the string reaches 0 long before limit reaches 1.

FWIW, here is a simpler solution to your problem:

fun truncate(s, n) = implode(List.take(explode s, n))