0

I have created a function in SML that traverses the starting elements of a list and if first,second,third.. element are the same deletes these elements and updates a variable's value.What i have written:

 let
    val min=7
 in
    fun seen2 (set:int list) =
    if hd set=hd(tl set) then 
    min=min-1
    seen2(tl set)  
    else 
    tl set
    end

The output of this function is meant to be a list with the elements i mentioned deleted.For example if it gets this list as input->[1,1,1,1,2,3,4] and min is set as 7 from before i excpect it to give [2,3,4] as a result and min to updated to 4.The min variable should be stored because this function will probably be called again and min may get further updated.This code gives me syntax errors.At the end the final min must be printed so i think this has to be something liek a global value(?).How could i accomplish this?

1 Answers1

2

traverses the starting elements of a list and if first,second,third.. element are the same deletes these elements

If by "first,second,third.." you mean arbitrarily many, then this is what you want to be doing:

fun removeDuplicatesBeginning [] = []
  | removeDuplicatesBeginning (x::y::zs) =
      if (* are the first two elements the same? *)
      then (* apply removeDuplicatesBeginning recursively
              to sub-list with one of them removed *)
      else (* no repeats, we're done recursing, only remove first element *)

Express your desired behavior using tests, e.g.

val test_1 = removeDuplicatesBeginning [1,1,1,1,2,3,4] = [2,3,4]

And don't forget corner cases, e.g.

val test_2 = removeDuplicatesBeginning [2,3,4] = [3,4]
val test_3 = removeDuplicatesBeginning [1,2,1] = [2,1]

Avoid...

  1. setting elements at the beginning, like let val min = 7 in ... end. There's no point.
  2. You can't write let ... in fun ... end, because fun ... is a declaration, and you can only have expressions between in and end for let. (The other thing is possible with local ... in ... end, but you still don't want to do this. There's no point.)
  3. using hd and tl. Use pattern matching on the input list's elements (x::xs, or x::y::zs).
sshine
  • 15,635
  • 1
  • 41
  • 66
  • Thank you sir for showing me the right way to do it using pattern matching.However i want to use min because this is a part of a larger program but with the local you suggested i have errors.what can i do? –  Apr 02 '19 at 13:02
  • @Leopardard: But you don't say what `min` is supposed to contain. I'd assume it would contain some *minimal* value, but in fact, your only two examples show that it's the *largest* values in your examples that get stored to `min`. So why don't you elaborate a bit on what the purpose of this value is? It's not the element that gets removed, and it's not the minimal element, and it's not the last element, and it's not the number of elements. I'm really running short of ideas here. :) – sshine Apr 03 '19 at 06:06