Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# version of Haskell's list destructuring

How do I do this haskell in F#:

f acc (x:y:z:xs) = f (acc-x+y*z) xs
f acc [] = acc

The algorithm there is arbitrary, just the important point is selecting the first 3 and the tail of the list because I need to use all of them and the tail.

Do I have to write it imperatively in F# using repeated head calls to pop off x y and z?

Edit: Please comment what this technique is formally called in haskell and I'll put it in the question title for other peoples future searches, I can't remember it off hand.

like image 784
Jimmy Hoffa Avatar asked Jul 26 '12 20:07

Jimmy Hoffa


2 Answers

What do you want to do when the pattern match fails? You probably want this:

let rec f acc = function
  | x::y::z::xs -> f (acc-x+y*z) xs
  | _ -> acc
like image 103
Daniel Avatar answered Nov 15 '22 20:11

Daniel


smth like this?

let rec f acc (x::y::z::xs) = f(acc - x + y * z) xs

but beware that this function will always end with MatchFailureException, because it will try to eagerly evaluate f until it reaches the tail that is lesser than 3 elements

like image 2
desco Avatar answered Nov 15 '22 18:11

desco