recursion - Simplify a recursive function from 3 to 2 clauses -


i doing exercises on f#, have function calculate alternate sum:

let rec altsum = function     | []         -> 0     | [x]        -> x     | x0::x1::xs -> x0 - x1 + altsum xs;;   val altsum : int list -> int 

the exercise consist in declare same function 2 clauses...but how this?

the answer of mydogisbox correct , work!

but after attempts found smallest , readable solution of problem.

let rec altsum2 = function | [] -> 0 | x0::xs -> x0 - altsum2 xs 

example

altsum2 [1;2;3] this: 1 - (2 - (3 - 0) 

it's bit tricky work!


off topic:

another elegant way solve problem, using f# list library is:

let altsum3 list = list.foldback (fun x acc -> x - acc) list 0;; 

after comment of phoog started trying solve problem tail recursive function:

let tail_altsum4 list =      let pl l = list.length l % 2 = 0     let rec rt = function             | ([],acc) -> if pl list -acc else acc         | (x0::xs,acc) -> rt (xs, x0 - acc)     rt (list,0) 

this bit tricky...substraction not commutative , it's impossible think revers list.rev long list...but found workaround! :)


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -