matrix - Adding 2 Int Lists Together F# -
i working on homework , problem 2 int lists of same size, , add numbers together. example follows.
vecadd [1;2;3] [4;5;6];; return [5;7;9]
i new , need keep code pretty simple can learn it. have far. (not working)
let rec vecadd l k = if l <> [] vecadd ((l.head+k.head)::l) k else [];;
i want replace first list (l) added numbers. have tried code different way using match cases.
let rec vecadd l k = match l |[]->[] |h::[]-> l |h::t -> vecadd ((h+k.head)::[]) k
neither of them working , appreciate can get.
first, idea modifying first list instead of returning new 1 misguided. mutation (i.e. modifying data in place) number 1 reason bugs today (used goto
, that's been banned long time now). making every operation produce new datum rather modify existing ones much, safer. , in cases may more performant, quite counterintuitively (see below).
second, way you're trying it, you're not doing think you're doing. double-colon doesn't mean "modify first item". means "attach item in front". example:
let = [1; 2; 3] let b = 4 :: // b = [4; 1; 2; 3] let c = 5 :: b // c = [5; 4; 1; 2; 3]
that's how lists built: start empty list , prepend items it. [1; 2; 3]
syntax you're using syntactic sugar that. is, [1; 2; 3] === 1::2::3::[]
.
so how modify list, ask? answer is, don't! f# lists immutable data structures. once you've created list, can't modify longer.
this immutability allows interesting optimization. take @ example posted above, 1 3 lists a
, b
, , c
. how many cells of memory think these 3 lists occupy? first list has 3 items, second - 4, , third - 5, total amount of memory taken must 12, right? wrong! total amount of memory taken these 3 lists actual 5 cells. because list b
not block of memory of length 4, rather number 4
paired pointer list a
. number 4
called "head" of list, , pointer called "tail". similarly, list c
consists of 1 number 5
(its "head") , pointer list b
, "tail".
if lists not immutable, 1 couldn't organize them this: if modifies tail? lists have copied every time (google "defensive copy").
so way lists return new one. you're trying can described this: if input lists empty, result empty list; otherwise, result sum of tails prepended sum of heads. can write down in f# verbatim:
let rec add b = match a, b | [], [] -> [] // sum of 2 empty list empty list | a::atail, b::btail -> (a + b) :: (add atail btail) // sum of non-empty lists sum of tails prepended sum of heads
note program incomplete: doesn't specify result should when 1 input empty , other not. compiler generate warning this. i'll leave solution exercise reader.
Comments
Post a Comment