Reputation: 322
What's the best way to insert an element in a list without returning a list? When I try to use the operator ::
, it returns a list:
element :: lst
However, I would like the return value to be unit, similar to the way Hashtbl.add
works.
Upvotes: 1
Views: 1550
Reputation: 1439
What you want to do can't be done because lists are not changeable.
They are not changeable because this is "exactly not" how you do things in functional programming. You give the original list to a function and get a new list. If the list is good for something you keep working on it.
But there is hope: you could use a reference. Code from an interactive session:
# let mylist = ["one";"two";"tree"] ;;
val mylist : string list = ["one"; "two"; "tree"]
# mylist.[1];;
Error: This expression has type string list
but an expression was expected of type string
# mylist.(1);;
Error: This expression has type string list
but an expression was expected of type 'a array
# List.iter (function e -> print_endline e) mylist;;
one
two
tree
- : unit = ()
# let r = ref [];;
val r : '_a list ref = {contents = []}
# r := "zero" :: mylist;;
- : unit = ()
# List.iter (function e -> print_endline e) !r;;
zero
one
two
tree
- : unit = ()
# List.iter (function e -> print_endline e) ("minus" :: !r);;
minus
zero
one
two
tree
- : unit = ()
# List.iteri (fun cnt -> fun e -> Printf.printf "Element %d: %s" cnt e) !r;;
Element 0: zeroElement 1: oneElement 2: twoElement 3: tree- : unit = ()
#
Code walk:
I am so explicit because I was missing exactly these examples when trying to get aquainted with FP.
/Str.
Upvotes: 1