简体   繁体   中英

Matlab “diff” in F# (subtract element by element)

There is a diff function in MATLAB, that computes difference between elements in vector (or matrix, but it is not the case now).

X = [1 1 2 3 5 8 13 21];
Y = diff(X)

Results in: 0 1 1 2 3 5 8

I came up with F# solution:

let x =[1;1;2;3;5;8;13;21]
let diff x = List.map2 (-) (x|> List.tail) (x|> List.take ((x|>List.length) - 1))

diff x

which results in same List, but I feel there should be a better way how to do difference in F#? Is there?

There's List.pairwise : 'T list -> ('T * 'T) list which gives you a list of consecutive pairs of items.

let x =[1;1;2;3;5;8;13;21]

let diff x =
    x |> List.pairwise |> List.map (fun (x, y) -> y - x)

Working with sequences instead of lists there is a compact solution:

let diff x = Seq.map2 (-) (Seq.skip 1 x) x

This would not work with lists because List.map2 requires its arguments to have the same length. Seq.map2 does not have that requirement.

For your specific case you could do:

[1;1;2;3;5;8;13;21] |> diff |> List.ofSeq

if you want the result to be a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM