質問

New to O'Caml, and I was playing around with lists, my goal is to do add elements, and make the existing list element point to its new value, that is if I have [4;6;7] that same list should become [4;10;17]

here is what I have so far:

let rec summation l curr  =
match l with [] -> l
| (x::xs) -> curr = x + curr
            x = curr;(*make the element in the list point to curr*)
summation xs curr ;;

I hope to invoke this function like summation [5;4;2] 0 and I feel like it should work.

役に立ちましたか?

解決

OCaml lists are immutable. You can't change them. There are ways to work with mutable data in OCaml--lists are immutable, but if you insist you could work with a list of mutable values. However, one of the reasons to study OCaml is to learn to work with immutable data. So that's what I'd suggest initially.

When working with immutable data, instead of changing your data you return a new version of the data that is different in the way you require. If your data is changing more than a little bit, you might want to use trees rather than lists.

Update

Let's say I want to calculate a list containing the squares of the values of my input list. One way to do it would be like this:

let rec squarelist l =
    match l with
    | [] -> []
    | h :: t -> (h * h) :: squarelist t

In essence, this function constructs a new list (using the :: operator) with the contents I want it to have. Usually you can use recursion to handle the tail of the list.

Your case is a little harder because you need to carry a cumulative sum. So you might need a helper function with an extra argument.

他のヒント

In addition to Jeffrey's answer, here is the correct code for your case

let summation l =
  let rec sum (acc,s) = function
    | [] -> List.rev acc
    | hd::tl -> let new_sum = hd+s in sum (new_sum::acc, new_sum) tl
  in 
  sum ([],0) l

Note that once you master the recursion and functional way, you should think about tail-recursive often, especially you don't mind some performance downgrading.


Re to your comment:

in always follows a let if necessary. Normally, we have let A in B, it means define something A in something B.

let in my code, in short it means let sum (acc,s)... in sum ([],0) l. I define a function which can used in the part after in.

function is a shortcut for match. If without function, I would write:

let rec sum (acc,s) l = 
    match l with
    | [] -> List.rev acc
    | hd::tl -> let new_sum = hd+s in sum (new_sum::acc, new_sum) tl

I suggest you read https://realworldocaml.org/, it is the best so far and newest book on ocaml, very good and comprehensive. It is free and you also can buy from Amazon.

Getting into OCaml's work is quite hard in the beginning. Especially, you need to understand what is functional way, comparing to the imperative way (like Java)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top