I'm struggling with some assignments in F# while I prepare for the exam.
The assignment says:
Consider the following F# declaration:
let rec f i = function | [] -> [i] | x::xs -> i+x :: f (i+1) xs
The type of
f
isint -> int list -> int list
. The expressionf 10 [0;1;2;3]
returns the value[10;12;14;16;14]
.The function
f
is not tail recursive. Declare a tail-recursive variant,fA
, off
using an accumulating parameter.AND
Declare a continuation-based tail-recursive variant,
fC
, off
.
So far I've tried something like:
let fA i =
let rec loop acc = function
| [] -> acc
| x::xs -> loop (i+x::acc) xs
loop i []
But I just can't see why it is not working with with these. I know I miss some deeper understanding on this, so now I try all the brains in here.
accumulator
Well you are almost there - first you might remember that the original
f
has 2 arguments - so you probably should add another:then the original changes
i
as it goes along - so you should too (add it to the loop):then you are almost there - you just have to call
loop
with the right arguments and maybe you have an order-problem ... keep trying :Dah yes - as @Sehnsucht said - somewhere you need to have the
i+1
in there ... well remember why you should take thei
with yourloop
....next hint
Ok seems you have some issues with your
acc
- well here is one more line - as you can see almost nothing changed:obviously you have to insert (different) things into the
???
places :Dif you have still trouble you can get a compiling version like this:
of course this will not work correctly but it will start you with something
continuation
you probably guessed it - the way from the accumulator-based to the continuation based is not to different (indeed this one might be easier - depending on how used you are to the backward-thinking):
start again with:
maybe you should let the compiler help you a bit if you have trouble - to do so add the type for
cont
like this:now remember that you will have to create new continuations as you go along - something like
(fun res -> ...something... |> cont)
to pass as the new continuations. Think ofres
as the result of doing my stuff with the rest of the list (yourxs
) then it should be easy.For the very first continuation you will most likely don't want to do anything at all ... but this is almost always the same so you will probably know it right away.
some mean points your teacher put in
[] -> [i]
can be nasty ... and yes you missed it right now ;) - once you got something compiling (should be your first concern) you will figure it out quite quickly I thinki+x
andi+1
... don't mix don't forget ;)PS: I don't want to spoil your homework to much - I'll make this into a full answer later - but it was to much/unreadable for a single comment IMO