blueblue
02-02-2005, 12:31 AM
Greetings.
I have the following problem set.
Trailing List Elements
Implement a function removeTrailing of type int * int list -> int list. The evaluation of removeTrailing(m, ilist) should return a list identical to the input list ilist except that all trailing occurrences of the integer m in the list have been removed. For example:
removeTrailing(6, [1, 4, 6, 3, 3, 6, 6]) returns [1, 4, 6, 3, 3]
removeTrailing(3, [3, 3, 3, 3, 3]) returns []
removeTrailing(3, [3, 3, 3, 3, 4]) returns [3, 3, 3, 3, 4]
removeTrailing(1, []) returns []
Now after doing some thinking and writing some code, I came up with the following code:
fun removeTrailing(a: int, nil): int list = nil
| removeTrailing(a: int, thelist: int list): int list =
let
fun internal(a: int, nil: int list): (int * int list) = (a, nil)
| internal(a: int, elem::rest: int list): (int * int list) =
let
val (b: int, newlist: int list) = internal(a, rest)
in
if a = elem andalso newlist = nil then (b, nil) else (b, elem::newlist)
end
in
let
val (_, return): (int * int list) = internal(a, thelist)
in
return
end
end;
Now despite the above code I wrote being extremely unoptimized, I know for sure it runs on the test cases, and more. However, I would love it if any of you could point out how to optimize. I wouldn't need a full-code if you don't want to provide me with any, but I'd just like a set of fresh-eyes to give me a different perspective.
Thanks!
I have the following problem set.
Trailing List Elements
Implement a function removeTrailing of type int * int list -> int list. The evaluation of removeTrailing(m, ilist) should return a list identical to the input list ilist except that all trailing occurrences of the integer m in the list have been removed. For example:
removeTrailing(6, [1, 4, 6, 3, 3, 6, 6]) returns [1, 4, 6, 3, 3]
removeTrailing(3, [3, 3, 3, 3, 3]) returns []
removeTrailing(3, [3, 3, 3, 3, 4]) returns [3, 3, 3, 3, 4]
removeTrailing(1, []) returns []
Now after doing some thinking and writing some code, I came up with the following code:
fun removeTrailing(a: int, nil): int list = nil
| removeTrailing(a: int, thelist: int list): int list =
let
fun internal(a: int, nil: int list): (int * int list) = (a, nil)
| internal(a: int, elem::rest: int list): (int * int list) =
let
val (b: int, newlist: int list) = internal(a, rest)
in
if a = elem andalso newlist = nil then (b, nil) else (b, elem::newlist)
end
in
let
val (_, return): (int * int list) = internal(a, thelist)
in
return
end
end;
Now despite the above code I wrote being extremely unoptimized, I know for sure it runs on the test cases, and more. However, I would love it if any of you could point out how to optimize. I wouldn't need a full-code if you don't want to provide me with any, but I'd just like a set of fresh-eyes to give me a different perspective.
Thanks!