PDA

View Full Version : Smlnj


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!

Sonarman
03-19-2005, 04:21 AM
Here's what I came up with. It's in Haskell, but translating it to SML should be straightforward.

removeTrailing n = fst . foldr aux ([], False)
where aux x (xs, False)
| x == n = (xs, False)
| otherwise = (x:xs, True)
aux x (xs, True) = (x:xs, True)

Edit: Just realized that it's been six weeks since the original post. Oh well.

blueblue
03-19-2005, 04:38 AM
Here's what I came up with. It's in Haskell, but translating it to SML should be straightforward.

removeTrailing n = fst . foldr aux ([], False)
where aux x (xs, False)
| x == n = (xs, False)
| otherwise = (x:xs, True)
aux x (xs, True) = (x:xs, True)

Edit: Just realized that it's been six weeks since the original post. Oh well.

No problem. Thanks for the effort, though!
I got the following lines to work in SML:

fun removeTrailing(_, []:int list):int list = []
| removeTrailing(m, x::tail) =
let
val rest:int list = removeTrailing(m, tail)
in
if (null rest) andalso x=m then []
else x::rest
end;


which ended being my final submission :)

kulpranav
04-28-2005, 06:43 PM
i am looking for help im ML programming. can you help me find a solution for following problem?

Write a program in ML that reads a string from a file and returns the substring in the input string with the largest mass. Mass is defined as the number of occurrences times its length.