6c656c
6c656c

Reputation: 322

How to add an element to a list without returning a list?

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

Answers (1)

Str.
Str.

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:

  • define mylist
  • try to access one element in the list, not possible
  • another try to access one element, no go. You must be able to access it to store a new value
  • example of list iteration to print a list
  • create reference r of type '_a list ref
  • store string and mylist in r
  • iterate list in r for printing, to see if the data is there
  • iterate list with on the fly change of the list
  • finally give a (poor) example of List.iteri, in Caml syntax

I am so explicit because I was missing exactly these examples when trying to get aquainted with FP.

/Str.

Upvotes: 1

Related Questions