smlsmlnj

SML: How to insert elements of a list into another list based on a value?


I have a list and a value, how can I insert elements of the list into a new list until sum of those elements won't exceed that value?

The question is how to return the aforementioned new list and initial list without elements of new list?

For example, I have a list [13,8,7,6,4,2,2,1] and a value 21. So, I want to insert the elements of that list into a new list which sum of them is less than or equal to 21. In this example a new list will be [13,8] and 13,8 must be removed from initial list.

so the final output of the function should be two lists: [13,8] , [7,6,4,2,2,1]

I have wrote the following function in SML ,but it has some confusing errors:

fun Scheduler (w:Wopt , L:PTList)=
    let
      val ptl1=[List.hd L]
      val TempL=L
      val head=List.hd L
    in
      if ListSum(ptl1) = w
      then (ptl1, Delete(L))
      else (
        if ListSum(ptl1) + head <= w 
        then Scheduler(Insert(head,ptl1), Delete(TempL))
        else (ptl1,Delete(L))
      ) 
    end

Solution

  • fun splitFor n [] = ([], [])
      | splitFor n (x::xs) =
        if x > n then ([], x::xs) else
        let val (ys, zs) = splitFor (n - x) xs
        in (x::ys, zs) end
    
    (* Example *)
    val (a, b) = splitFor 21 [13,8,7,6,4,2,2,1]