Reputation: 1
In SOSML Write the following ML functions using, whenever possible, pattern-matching function definitions.
Function union of type 'a list * 'a list → 'a list that returns the union of two lists (in any order). For example union ([3, 4, 7, 9, 8, 5], [5, 7, 6, 2, 1, 8, 9]) should return [3, 4, 7, 9, 8, 5, 6, 2, 1] (in any order).
Function quicksort of type int list → int list that sorts the given list of integers using the quick-sort algorithm. For example: quicksort [3, 4, 7, 9, 8, 5, 6, 2, 1] should return [1, 2, 3, 4, 5, 6, 7, 8, 9].
In #1 I am getting this error when I run my code on sosml.org: Elaboration failed: Unbound value identifier "member". Here's my code:
fun union ([], ys) = ys
| union (x::xs, ys) = if member (x, ys) then union (xs, ys) else x :: union (xs, ys);
(* Test case for the union function *)
val test_union = union ([3, 4, 7, 9, 8, 5], [5, 7, 6, 2, 1, 8, 9]);
(* Should return a list containing all elements from both lists without duplicates and in any order *)
In #2 I am getting this error: val quicksort = fn: ∀ 'b . int list → 'b list; Execution terminated due to time limit violation
this is my code:
fun quicksort [] = []
| quicksort (x::xs) =
let
fun partition (pivot, less, equal, greater) =
case less of
[] => (equal, greater)
| y::ys => if y < pivot then partition (pivot, ys, equal, y::greater)
else if y = pivot then partition (pivot, ys, y::equal, greater)
else partition (pivot, ys, y::less, greater);
val (less, greater) = partition (x, [], [x], xs)
in
quicksort less @ quicksort greater
end;
(* Test case for the quicksort function *)
val test_quicksort = quicksort [3, 4, 7, 9, 8, 5, 6, 2];
(* Should return [2, 3, 4, 5, 6, 7, 8, 9] *)
Upvotes: 0
Views: 79