Inserting tuples in a list Ocaml -


i have declared list l=[];; , trying append tuples list using '@'. not able so. can please me sorting out.

let l = [] x = 1 10   l <- l@[(x,x+10)]   done;; 

and want final answer as: l=[(1,10),(2,20),(3,30).....]

your definition of l means l immutable. define value [], , can never changed.

if want able change l, need define mutable value. 1 simple way make "ref":

# let l = ref [];; val l : '_a list ref = {contents = []} 

after can value of l ! operator , change value using := operator:

# !l;; - : '_a list = [] # l := !l @ [3];; - : unit = () # !l;; - : int list = [3] 

however, code not idiomatic ocaml. if you're studying ocaml academically, might better learn work immutable values.

update

here hints on writing recursive functions. don't want spoil exercise writing code you.

the way solve problem recursively answer questions this:

  1. what general problem trying solve? in case, you're trying create list of pairs of length arithmetic properties.

  2. what trivial case of problem? in case, trivial case when desired length 0 (in case list empty).

  3. if have non-trival case of problem, how can break calculated answers , smaller cases of same problem? want assemble these full answer. in case, smaller pieces first element of result (easily calculated), , list that's 1 shorter (smaller case of same problem).

then code looks garden variety recursive function number of parameters (say a, b, c, d):

let rec f b c d =     if <<this trivial case>>         <<the answer obvious>>     else         let tp = <<answer tiny piece of problem>> in         let (a', b', c', d') = <<rest of problem (smaller)>> in         let smres = f a' b' c' d' in         <<combine tp , smres>> 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -