I am currently working in ml and am a little stuck here:: I have a
sorted list to traverse, find a value in and modify a value
of ,without disturbing any ordering. I am currently working in ML,
then lisp and prolog. I could answer this question for C or java how
would a functional programmer approach this problem?
Thanks!
kris
Is this homework? Anyway, if I understand your question correctly,
then this 2-liner suffices (in SML):
fun update x x' nil = nil
| update x x' (y::ys) = (if y = x then x' else y) :: update x x' ys
This works for any list, sorted or not. I'm not sure what you meant by
"sorted", because the function you describe will generally not
maintain sortedness.
If you really meant sorted and wanted to break out early once y gets
larger than x then you typically need to know the element type, or
pass in a comparison function as extra argument. In OCaml you can get
away with polymorphic comparison:
let rec update x x' = function
| [] -> []
| y::ys when x = y -> x'::ys
| y::ys when x < y -> y::ys
| y::ys -> y::update x x' ys
This assumes that x occurs at most once. But as said, you generally
get back a list that is no longer sorted.
- Andreas
OCaml:
To produce a new list:
# let list = [2;3;5;8;13];;
val list : int list = [2; 3; 5; 8; 13]
# List.map (fun x -> if x=5 then 900 else x) list;;
- : int list = [2; 3; 900; 8; 13]
An array can easily be changed:
# let ary = [|2;3;5;8;13|];;
val ary : int array = [|2; 3; 5; 8; 13|]
# for i = 0 to pred (Array.length ary) do
if 5 = ary.(i) then ary.(i) <- 900
done;;
- : unit = ()
# ary;;
- : int array = [|2; 3; 900; 8; 13|]