Member variables in F# - f#

let eval a b =
let r = a + b
printf "calculate.."
r
type Foo() =
member this.Eval = eval 5 10
[<EntryPoint>]
let main argv =
let f = Foo()
let a = f.Eval
let b = f.Eval
0
This calls eval 2 times instead of one time. It seems this.Eval is a function pointer that calls eval every time I call .Eval.
What I really want to have is a variable.
I solved it by doing this...
let eval a b =
let r = a + b
printf "calculate.."
r
type Foo() =
let e = eval 5 10
member this.Eval = e
[<EntryPoint>]
let main argv =
let f = Foo()
let a = f.Eval
let b = f.Eval
0
Is this the correct way of doing this if I just want to have a member variable instead of method?

The behaviour you describe is the way .NET properties always work, whether in C# or F#. The body of the property is evaluated each time the property is read.
In addition to your solution, which is correct, I'd add that it calculates the value when Foo is constructed. You might only want the value to be calculated when you read the property the first time, and if so you can use Lazy to do that:
let eval a b =
let r = a + b
printf "calculate.."
r
type Foo() =
// a lazy computation that will be evaluated the first time .Value is called
let e = lazy eval 5 10
member this.Eval = e.Value
[<EntryPoint>]
let main argv =
let f = Foo()
let a = f.Eval
let b = f.Eval
0

I think that the more idimatic F# style would be:
type Foo() =
let eval a b =
let r = a + b
printf "calculate.."
r
let e = eval 5 10
member this.Eval = e
[<EntryPoint>]
let main argv =
let f = Foo()
let a = f.Eval
let b = f.Eval
0
i.e. you put the eval inside the class with a let binding to hide the implementation

Related

How to make a lazy computational workflow?

I'm trying to write a computational workflow which would allow a computation which can produce side effects like log or sleep and a return value
A usage example would be something like this
let add x y =
compute {
do! log (sprintf "add: x = %d, y= %d" x y)
do! sleep 1000
let r = x + y
do! log (sprintf "add: result= %d" r)
return r
}
...
let result = run (add 100 1000)
and I would like the side effects to be produced when executeComputation is called.
My attempt is
type Effect =
| Log of string
| Sleep of int
type Computation<'t> = Computation of Lazy<'t * Effect list>
let private bind (u : 'u, effs : Effect list)
(f : 'u -> 'v * Effect list)
: ('v * Effect list) =
let v, newEffs = f u
let allEffects = List.append effs newEffs
v, allEffects
type ComputeBuilder() =
member this.Zero() = lazy ((), [])
member this.Return(x) = x, []
member this.ReturnFrom(Computation f) = f.Force()
member this.Bind(x, f) = bind x f
member this.Delay(funcToDelay) = funcToDelay
member this.Run(funcToRun) = Computation (lazy funcToRun())
let compute = new ComputeBuilder()
let log msg = (), [Log msg]
let sleep ms = (), [Sleep ms]
let run (Computation x) = x.Force()
...but the compiler complains about the let! lines in the following code:
let x =
compute {
let! a = add 10 20
let! b = add 11 2000
return a + b
}
Error FS0001: This expression was expected to have type
'a * Effect list
but here has type
Computation<'b> (FS0001)
Any suggestions?
The main thing that is not right with your definition is that some of the members of the computation builder use your Computation<'T> type and some of the other members use directly a pair of value and list of effects.
To make it type check, you need to be consistent. The following version uses Computation<'T> everywhere - have a look at the type signature of Bind, for example:
let private bind (Computation c) f : Computation<_> =
Computation(Lazy.Create(fun () ->
let u, effs = c.Value
let (Computation(c2)) = f u
let v, newEffs = c2.Value
let allEffects = List.append effs newEffs
v, allEffects))
type ComputeBuilder() =
member this.Zero() = Computation(lazy ((), []))
member this.Return(x) = Computation(lazy (x, []))
member this.ReturnFrom(c) = c
member this.Bind(x, f) = bind x f
member this.Delay(funcToDelay:_ -> Computation<_>) =
Computation(Lazy.Create(fun () ->
let (Computation(r)) = funcToDelay()
r.Value))

How to execute specific functions with input pattern in F# language

I'm kinda new to F# and trying out a simple calculator app. I take input from the user, and I want to the specific functions to be executed as per the input.
Right now, whenever I take any input from user, the program executes top to bottom. I want it to execute only specific functions matching with the input. Like if input is 6 then body of scientificFun() should be executed. Right now it executes all functions. Please help, I'm kinda stuck on this one!
The code is
open System
let mutable ok = true
while ok do
Console.WriteLine("Choose a operation:\n1.Addition\n2.Substraction\n3.Multiplication\n4.Division\n5.Modulo\n6.Scientific")
let input= Console.ReadLine()
let add =
Console.WriteLine("Ok, how many numbers?")
let mutable count = int32(Console.ReadLine())
let numberArray = Array.create count 0.0
for i in 0 .. numberArray.Length - 1 do
let no = float(Console.ReadLine())
Array.set numberArray i no
Array.sum numberArray
let sub x y = x - y
let mul x y = x * y
let div x y = x / y
let MOD x y = x % y
let scientificFun() =
printfn("1. Exponential")
match input with
| "1" -> printfn("The Result is: %f") (add)
| "6" -> (scientificFun())
| _-> printfn("Choose between 1 and 6")
Console.WriteLine("Would you like to use the calculator again? y/n")
let ans = Console.ReadLine()
if ans = "n" then
ok <- false
else Console.Clear()
You should define add as function: let add() = or let add inputNumbers =
Otherwise this simplified version below only executes the functions corresponding to the input number:
open System
[<EntryPoint>]
let main argv =
// define your functions
let hellofun() =
printfn "%A" "hello"
let worldfun() =
printfn "%A" "world"
let mutable cont = true
let run() = // set up the while loop
while cont do
printfn "%A" "\nChoose an operation:\n 1 hellofunc\n 2 worldfunc\n 3 exit"
let input = Console.ReadLine() // get the input
match input with // pattern match on the input to call the correct function
| "1" -> hellofun()
| "2" -> worldfun()
| "3" -> cont <- false;()
| _ -> failwith "Unknown input"
run() // kick-off the loop
0
The [<EntryPoint>] let main argv = is only necessary if you compile it. Otherwise just execute run().

Injecting a function into a computation expression

The following code sample is from Scott Wlaschin's site F# for fun and profit.
type LoggingBuilder() =
let log p = printfn "expression is %A" p
member this.Bind(x, f) =
log x
f x
member this.Return(x) =
x
let logger = new LoggingBuilder()
let loggedWorkflow =
logger
{
let! x = 42
let! y = 43
let! z = x + y
return z
}
Is there a way to inject a function instead of printfn into the LoggingBuilder()?
You can just add a parameter to the builder type:
type LoggingBuilder(lf: obj -> unit) =
let log p = lf p
member this.Bind(x, f) =
log x
f x
member this.Return(x) =
x
let logger = new LoggingBuilder(printfn "expression is %A")
You could make the builder generic if you want to make the input type more specific than obj e.g.
type LoggingBuilder<'a>(lf: 'a -> unit) =
...
let logger = new LoggingBuilder<int>(printfn "Got %i")
If your intention is to replace printfn with a logger such as NLog, you can use Printf.ksprintf.
open NLog
open NLog.Config
open NLog.Targets
let private logger =
let config = new LoggingConfiguration()
let consoleTarget = new ColoredConsoleTarget()
config.AddTarget("console", consoleTarget)
consoleTarget.Layout <- Layouts.SimpleLayout.FromString
#"${longdate}|${level:uppercase=true}|${logger}|${message}"
let rule = new LoggingRule("*", LogLevel.Debug, consoleTarget)
config.LoggingRules.Add rule
LogManager.Configuration <- config
LogManager.GetLogger "MyLogger"
type LoggingBuilder(lf: string -> unit) =
let log format =
let doAfter (s: string) = lf s
Printf.ksprintf doAfter format
member this.Bind(x, f) =
log "%A" x
f x
member this.Return(x) =
x
let logger = new LoggingBuilder(logger.Info)

The mutable variable 'x' is used in an invalid way. Mutable variables cannot be captured by closures

I have a couple of books that I am going by, but as I am working on my F# problems, I find some difficulties in syntax here. If anyone thinks I should not be asking these questions here and have another book recommendation on a budget, please let me know.
Here is the code that reproduces the problem I am having with my project
[<EntryPoint>]
let main argv =
let mutable x = 0
let somefuncthattakesfunc v = ignore
let c() =
let y = x
ignore
somefuncthattakesfunc (fun () -> (x <- 1))
Console.ReadKey()
0 // return an integer exit code
I am getting the following compile error
The mutable variable 'x' is used in an invalid way. Mutable variables cannot be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via 'ref' and '!'.
Any clue ?
As the error explains, you can't close over mutable variables, which you are doing in:
let y = x
and
(fun () -> x = 1)
It suggests you use a ref instead if you need mutation:
let x = ref 0
let somefuncthattakesfunc v = ignore
let c() =
let y = !x
ignore
somefuncthattakesfunc (fun () -> x := 1)
As the error message says, mutable variables cannot be captured by closures, use a reference cell instead:
let main argv =
let x = ref 0
let somefuncthattakesfunc v = ignore
let c() =
let y = !x
ignore
somefuncthattakesfunc (fun () -> x := 1)
Console.ReadKey()
0 // return an integer exit code
Also see this answer.

F# compose pattern matched function

I have these types:
type ShouldRetry = ShouldRetry of (RetryCount * LastException -> bool * RetryDelay)
and RetryCount = int
and LastException = exn
and RetryDelay = TimeSpan
type RetryPolicy = RetryPolicy of ShouldRetry
Now I want composability of the retries; something like this:
let serverOverloaded = [| exnRetry<TimeoutException>;
exnRetry<ServerBusyException> |]
|> Array.map (fun fn -> fn (TimeSpan.FromSeconds(4.0)))
let badNetwork = [||] // etc
let compose p1 p2 =
// http://fssnip.net/7h
RetryPolicy(ShouldRetry( (fun (c,e) ->
let RetryPolicy(ShouldRetry(fn)) = p1
let RetryPolicy(ShouldRetry(fn')) = p2
let (cont, delay) = fn c,e
if cont then cont, delay
else
let (cont', delay') = fn' c,e
cont', delay') ))
let finalPolicy = serverOverloaded |> Array.scan compose (RetryPolicies.NoRetry())
But I'm getting compiler errors on fn, delay and fn', saying "The value or constructor 'fn' is not defined".
I can see two problems in your compose function.
When decomposing p1 and p2, the pattern needs to be wrapped in parentheses (otherwise, the compiler interprets the code as a definition of RetryPolicy function, instead of pattern matching):
let (RetryPolicy(ShouldRetry(fn))) = p1
let (RetryPolicy(ShouldRetry(fn'))) = p2
When calling fn' a bit later, you need to pass it the arguments in a tuple (otherwise, the compiler thinks that you're calling fn' with just a single argument c and then building a tuple):
let (cont', delay') = fn' (c,e)
I didn't check (or tried to run) the whole example, so I don't know if the rest of the code does what you want.

Resources