functional programming - how return a new type with an update value -
if want change value on list, return new list new value instead of changing value on old list.
now have 4 types. need update value location in varend, instead of changing value, need return new type update value
type varend = { v: ctype; k: varkind; l: location; } ;; type varstart = { ct: ctype; sy: stable; n: int; stm: stmt list; e: expr } , sentry = var of varend | fun of varstart , stable = (string * sentry) list type environment = stable list;; (a function environment parameter can use) let allocatemem (env:environment) : environment =
i tried use list.iter, changes value directly, type not mutable. think list.fold better option.
the biggest issue have there 4 different types.
i think you're saying know how change element of list constructing new list.
now want environment, , environment list of quite complicated things. doesn't make difference, way change list same. difference replacement value complicated thing.
i don't know mean when have 4 types. see lot more 4 types listed here. on other hand, environment seems contain things of 2 different types.
maybe (but possibly not) you're saying don't know way change 1 of 4 fields of record while leaving others same. there's answer. assume x of type varend
. can say:
{ x l = loc }
if, in fact, don't know how modify element of list creating new list, that's thing figure out first. can fold, in fact can list.map
, little simpler. can't list.iter
.
update
assume have record type this:
type r = { a: int; b: float; }
here's function takes r list list
, adds 1.0 b
fields of records a
fields 0.
let incr_ll rll = let f r = if r.a = 0 { r b = r.b +. 1.0 } else r in list.map (list.map f) rll
the type of function r list list -> r list list
.
Comments
Post a Comment