f# - Conversion to tail recursion -
hey guys, i'm trying cozy functional programming (particularly f#), , i've hit wall when comes building tail-recursive functions. i'm pretty turning basic recursion (where function calls once per invocation), tail recursion, have more complicated situation.
in case, function must accept single list parameter. when function called, have remove first element list, , recur using remainder of list. need apply first element removed in way result of recursion. next, remove second element , same thing (note: when "remove seond element", original list, list passed @ recursion includes first element well). same third, fourth, etc. elements of list.
is there way convert above situation tail-recursive function? maybe nested tail-recursive functions??? thank answers.
okay, here's basic code. particular 1 permutation generator (i'm not concern permutation part, though - it's recursion i'd focusing on):
let permutationsother str = match str | value :: [] -> [[value]] | _ -> let list = (list.map (fun -> // applies remove part every element let lst = (list.filter (fun b -> b <> a) str) // part removes element list let permutedlst = permutations lst // recursive call constoall permutedlst // consttoall own function performs "cons" operation , every element in list permutedlst ) str) list.reduce (fun acc elem -> elem @ acc) list // flatten list of lists produce map single list i hope clear enough - i'll happy provide clarifications if needed.
by way, have found way rewrite particular function uses single recursion, fluke more informed decision. however, has encouraged me there may general method of turning multiple recursion single recursion, have not yet found it.
conversion cps should trick:
note 1: source of sample typed directly in browser, may contain errors :(. hope can demonstrate general idea.
note 2: constoall function should converted cps too: constoall: 't -> 't list list -> ('t list list -> 'r) -> 'r
let remove x l = list.filter ((<>) x) l // original post: should duplicates removed ??? let permute l = let rec loop k l = match l | [] -> k [] | [value] -> k [[value]] | _ -> filter l [] l (fun r -> r |> list.reduce (fun acc elem -> elem @ acc) |> k ) , filter l acc orig fk = match l | [] -> fk acc | x::xs -> remove x orig |> loop (fun res -> constoall x res (fun rs -> filter xs (rs::acc) orig fk) ) loop id l
Comments
Post a Comment