F# Recursive Member Function : "How to Define it correctly" - recursion

I it is my understanding that when you define a recursive member function within a type then there is no need to define the function to be recursive. Meaning use of the rec keyword.
however when i do this:
type hello() = class
member this.recursion(x) =
match x with
|10 -> printfn "%A" x
|_ -> printfn "%A" x
recursion(x+1)
end
Then i get the error that recursion is not defined.
I have tried this.recursion but then i still get a warning saying:
The recursive object reference 'this' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference.
So i am wondering what is the correct way to define a recursive member function within a type?

Yes, they work when defined as members.
As you already noticed, you're missing the this at the call site. It should be:
this.recursion(x+1)
But this works well, at least for me:
type hello() = class
member this.recursion(x) =
match x with
|10 -> printfn "%A" x
|_ -> printfn "%A" x
this.recursion(x+1)
end
Anyway I would define it internally, as showed in the other answer but inside the method:
type hello() = class
member this.recursion(x) =
let rec loop x =
match x with
|10 -> printfn "%A" x
|_ -> printfn "%A" x
loop (x+1)
loop x
end

You can define normal recursive function within the body of your class (it will be private function) and then expose it as member, example:
type Hello() =
let rec recursion x =
match x with
| 1 -> printfn "%A" x
| _ -> printfn "%A" x; recursion (x+1)
member this.Recursion(x) = recursion x

Related

recursive stack overflow with exceptions in F#

let's look at that code:
let rec doSomething () =
let d = GetSomeDataFromSomewhere()
match d with
| Some x -> x
| None -> doSomething()
so that's some form of non stop polling..
but now the following form:
let rec doSomething () =
try
let d = GetSomeDataFromSomewhereButItCouldCrash()
match d with
| Some x -> x
| None -> doSomething()
with _ ->
doSomething()
that one will lead to a stack overflow if there are a lot of exceptions.
Can someone explain the mechanics at play that make the two versions behave differently?
The issue is that the first call in your second version is not in a tail-call position. This is not entirely obvious, because the recursive call is the "last thing the function does", but the runtime still has to keep the stack frame around, because it needs to keep the associated exception handler.
let rec doSomething () =
try
let d = GetSomeDataFromSomewhereButItCouldCrash()
match d with
| Some x -> x
| None -> doSomething() // This is not a tail call!
with _ ->
doSomething() // This is a tail call
If you handle exceptions directly when calling GetSomeDataFromSomewhere and turn them into None, then you can keep the same logic, but make it tail recursive:
let rec doSomething () =
let d = try GetSomeDataFromSomewhereButItCouldCrash() with _ -> None
match d with
| Some x -> x
| None -> doSomething()

How to iterate a stream in Ocaml

I am trying to iterate through a stream in order to print the content.
type 'a stream = Nil | Cons of 'a * 'a stream thunk and 'a thunk = unit -> 'a
This is where my function is called
|> iter_stream ~f:(fun (f,c,l) -> printf "%s %s %s\n" f c l)
And this is the type
let rec iter_stream st ~f
(* val iter_stream : 'a stream -> ('a -> unit) -> unit *)
I can't seem to find any examples on how to implement it. The only idea I have is to think about it like a list which is obviously wrong since I get type errors.
let rec iter_stream st ~f =
match st with
| None -> ()
| Some(x, st') -> f x; iter_stream st' ~f
Your stream is extremely similar to a list, except that you need to call a function to get the tail of the list.
Your proposed code has many flaws. The main two flaws that I see are:
You're using the constructors None and Some while a stream has constructors Nil and Cons.
You're not calling a function to get the tail of the stream. Note that in Cons (a, b), b is a "stream thunk", i.e., it's a function that you can call to get a stream.
(Perhaps these are the only two flaws :-)
I hope this helps.

Function with an arbitrary number of arguments in F#

I want to write a function that will take an arbitrary number of (curried) arguments and simply print them out (or perform some other unspecified action with them). Here is what I have come up with:
let print arg =
let rec print args arg =
if not (FSharpType.IsFunction(typeof<'t>)) then
printfn "%A" args
Unchecked.defaultof<'t>
else
print (box arg::args)
print []
When I try to compile this I get the error The resulting type would be infinite when unifying ''t' and ''a -> 't.
I know I could just pass the arguments as a list, but I am trying to develop an API of sorts where this would be a useful idiom to have.
Is there some clever compiler trick to make such a function possible in F# or is it a lost cause?
It seems that the two branches of the inner print want to return different types: the "then" part wants to return 't, but the "else" part wants to return 'a -> 't, where 't is necessarily the same in both branches. That is, your function tries to return either its own return type or a function from another type to its own return type. Such combined return type would, indeed, be infinite, which is in perfect accordance with what you set out to do - namely, create a function with infinite number of arguments. Though I do not know how to formally prove it, I would say this is indeed impossible.
If your goal is to simply create a list of boxed values, you could get away with defining a few infix operators.
let (<+>) a b = a # [(box b)]
let (<&>) a b = [(box a); (box b)]
let xs = 5 <&> "abc" <+> 3.0 <+> None <+> true
>> val xs : obj list = [5; "abc"; 3.0; null; true]
Alternatively, with carefully chosen operator precedence, you can apply a function (but then you'll need a terminator):
let (^>) a b = (box a)::b
let (<&>) f xs = f xs
let print xs = sprintf "%A" xs
let xs = print <&> 5 ^> "abc" ^> 3.0 ^> None ^> true ^> []
>> val xs : string = "[5; "abc"; 3.0; null; true]"

F#: Using object expression with discriminated union

I have a recursive function that contains a series of matches that either make the recursive call back to the function, or make a call to failwith.
This is basically a hybrid implementation of the recursive descent parser descibed in Don Syme's Expert F# book (page 180) and the parsing example shown here: http://fsharpforfunandprofit.com/posts/pattern-matching-command-line/
Here is a snippet of my own code.
let rec parseTokenListRec tokenList optionsSoFar =
match tokenList with
| [] -> optionsSoFar
| SOURCE::t ->
match t with
| VALUE x::tt -> parseTokenListRec (returnNonValueTail t) {optionsSoFar with Source = (returnConcatHeadValues t)}
| _ -> failwith "Expected a value after the source argument."
| REGISTRY::t ->
...
A full code listing can be found at http://fssnip.net/nU
The way the code is currently written, when the function has finished working its way through the tokenList, it will return the optionsSoFar record that has been compiled via the object expression {optionsSoFar with Source = (returnConcatHeadValues t)}, or it will throw an exception if an invalid argument is found.
I want to refactor this so that the function does not rely on an exception, but will always return a value of some sort that can be handled by the calling function. The idea I have is to return a discriminated union rather than a record.
This discriminated union would be something like
type Result =
|Success of Options
|Failure of string
The problem I had when I tried to refactor the code was that I couldn't figure out how to get the success value of the DU to initialize via an object expression. Is this possible?
The examples I've looked at on MSDN (http://msdn.microsoft.com/en-us/library/vstudio/dd233237(v=vs.100).aspx), fsharpforfunandprofit (http://fsharpforfunandprofit.com/posts/discriminated-unions/) and elsewhere haven't quite cleared this up for me.
I'm worried that I'm not making any sense here. I'm happy to clarify if needed.
If I understand it correctly, in you current solution, the type of optionsSoFar is Options. The code becomes trickier if you change the type of optionsSoFar to your newly defined Result.
However, I think you do not need to do that - you can keep optionsSoFar : Options and change the function to return Result. This works because you never need to call the function recursively after it fails:
let rec parseTokenListRec tokenList optionsSoFar =
match tokenList with
| [] -> Success optionsSoFar
| SOURCE::t ->
match t with
| VALUE x::tt ->
{optionsSoFar with Source = (returnConcatHeadValues t)}
|> parseTokenListRec (returnNonValueTail t)
| _ -> Failure "Expected a value after the source argument."
| REGISTRY::t -> ...
If you actually wanted to update Source in a Result value, then I'd probably write something like:
module Result =
let map f = function
| Success opt -> f opt
| Failure msg -> Failure msg
Then you could write a transformation as follows:
resultSoFar
|> Result.map (fun opts -> {opts with Source = returnConcatHeadValues t})
|> parseTokenListRec (returnNonValueTail t)

Retrieving attributes from a function argument

If I have a function that takes in another function:
[<SomeAttribute()>]
let f (g:unit->unit) =
//Want to get g's custom attributes
How can I access g's custom attributes from f?
I think I'm missing something really obvious here.
This is not in general possible, because when you use a function as an argument (e.g. f foo), the F# compiler wraps the foo value into some object. Extracting the actual method reference foo from this object would be very difficult (and it would work only if the compiler didn't do some optimizations).
However, you can get the desired behavior using F# quotations. Instead of taking a function unit -> unit, your f can take a quoted function Expr<unit -> unit>. You can then call the function using f <# foo #> and the function can extract the method refernce and also call foo.
Here is an example. It requires reference to F# PowerPack (so that it can evaluate the quotation). In this simple case, the evaluation should be quite efficient:
#r #"FSharp.PowerPack.Linq.dll"
type SomeAttribute(name:string) =
inherit System.Attribute()
member x.Name = name
// Example function with some attribute
[<SomeAttribute("Test")>]
let g () = printfn "Hello"
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation
// Takes a quotation instead of a function value
let f (g:Expr<unit->unit>) =
// Extract method info & attributes from the quotation
match g with
| DerivedPatterns.Lambdas(_, Patterns.Call(_, mi, _)) ->
let attrs = mi.GetCustomAttributes(typeof<SomeAttribute>, false)
for a in attrs |> Seq.cast<SomeAttribute> do
printfn "%A" a.Name
| _ ->
failwith "Argument must be of the form <# foo #>!"
// Compile the function so that it can be executed (the compilation
// takes some time, but calling invoke should be fast)
let invoke = g.Compile()()
invoke()
invoke()
// And this is how you call the function
f <# g #>
let f (g:unit->unit) =
printfn "%d" (g.GetType().GetCustomAttributes(true).Count())

Resources