This expression was expected to have type 'double' but here has type 'unit'

Ive an array of integers, and want to do the following operation:

s += array(index+1) - array(index)

so, I tried the below:

let mutable s =0
for i in 0 .. slen-1 do
s <- series.[i+1] - series.[i] + s

but I goy an error:

This expression was expected to have type 'double' but here has type 'unit'

UPDATE

The full code

let series = [|30;21;29;31;40;48;53;47;37;39;31;29;17;9;20;24;27;35;41;38;
          27;31;27;26;21;13;21;18;33;35;40;36;22;24;21;20;17;14;17;19;
          26;29;40;31;20;24;18;26;17;9;17;21;28;32;46;33;23;28;22;27;
          18;8;17;21;31;34;44;38;31;30;26;32|]

let initialTrend series slen : double=
    let mutable s = 0
    for i in 0 .. slen-1 do
    s <- series.[i+1] - series.[i] + s

1 answer

  • answered 2018-01-13 17:49 Gustavo

    Well, you are telling that the function will return a double and the error message is telling you that it doesn't return anything, that's correct.

    Either, remove the return type:

    let initialTrend series slen : unit =
      let mutable s = 0
      for i in 0 .. slen-1 do
        s <- series.[i+1] - series.[i] + s
    

    or change the way the function works:

    let initialTrend (series: _ list) slen : double=
        let mutable s = 0
        for i in 0 .. slen-1 do
            s <- series.[i+1] - series.[i] + s
        float s
    

    But, looking at your recent questions, you are still sticking to mutability. I would suggest to use a higher order function here instead:

    let initialTrend (series: float [])  : double =
        Array.pairwise series |> Array.fold (fun s (x0, x1) -> x1 - x0 + s) 0.