views:

352

answers:

3

I'm having trouble with lists in OCaml. I've read conflicting statements saying whether or not the lists can be modified at runtime. Can the cons operator be used at runtime?

Additionally, why is a doberman (see below) allowed to be in a list of chihuahuas? How would one go about adding another chihuahua onto the list (as attempted with the last line)?

class virtual dog =
object
 method virtual bark : unit
end;;

class chihuahua =
object
 inherit dog
 method bark = Printf.printf "Yip!"

end;;

class doberman =
object
 inherit dog
 method bark = Printf.printf "Roar!"

end;;

let c1 = new chihuahua;;
let c2 = new chihuahua;;
let c3 = new chihuahua;;
let d1 = new doberman;;

let arrayOfDogs = [c1;c2;d1];;
arrayOfDogs :: c3;;
+3  A: 

you need to have your list on the right hand side, not the left. Ie:

c3 :: arrayOfDogs;;

This is why the last line fails.

As far as the list construction goes, given that OCaml is type-inferred, the interpreter probably figured out that you're constructing a list of dogs given you added the doberman on construction. Therefore it's not a list of Chihuahuas.

OJ
+1  A: 

What does OCaml report as the type of arrayOfDogs?

Perhaps you mean: c3 :: arrayOfDogs;;

Doug Currie
+4  A: 

1) You can use the cons operator at runtime, it just returns a new list rather than mutating the input list.

2) Class types in OCaml use "structural" subtyping, rather than Java-style "nominal" subtyping. The inferred type of arrayOfDogs will be "an object with a method named bark of type unit -> unit (not necessarily a dog)". For example:

# class cat = object 
    method bark = print_endline "meow" 
  end ;;
class cat : object method bark : unit end
# let c = new cat ;;
val c : cat = <obj>
# c :: arrayOfDogs ;;
- : cat list = [<obj>; <obj>; <obj>; <obj>]

3) The problem with arrayOfDogs :: c3 is you've got it the wrong way around. The type of :: is 'a -> 'a list -> 'a list. To add c3 at the beginning, use

c3 :: arrayOfDogs

To add it at the end, use the "append" operator @

arrayOfDogs @ [c3]
Chris Conway