Return Data From Function F# - f#

I'm new to F#. I have a Function that does some database operation. I am struggling returning result.
let funcA () =
let funcB () =
// do some database operation and returns seq of records
let funcC () =
// do some other database operation returns nothing
let result = funcB ()
funcC ()
How can I return result from funcA? I need to execute funcB before funcC

The last line of the function should be your return value. In your case you don't necessarily need to nest functions here, but we can leave it as is. Also, it's important to note that F# is an eagerly-evaluated language by default, so if you define your functions without any parameters they will actually be evaluated up front (and will not change with future executions). If you do not actually require any paramters for your function, then provide a unit value as your parameter.
let funcA () = // Function defintion
instead of
let funcA = // Function definition
let funcA () =
let funcB () =
// Perform database operation
let funcC () =
// Perform some side-effect, returns ()
let result = funcB ()
funcC ()
result // This will be your return value
let a = funcA () // Example usage

The accepted answer works fine, but it is not very fsharp-y
If your funcC may only be executed after funcB, this can be made more explicit by using the result type of funcB as input to funcC. Or even better, use the railway pattern:
let funcA () =
let funcB () : Result<Seq<Foo>, string> =
// perform database operation, return Ok <| sequence of Foo if successful
// otherwise Error <| "sql failed"
let funcC x =
// perforn some side effect
x //return input
funcB ()
|> Result.map funcC
( See Scott Wlaschins excellent posts about railway oriented programming )

Related

Is it possible to write a generic based on a record with a named field?

I have some code which has a lot of repetition.
type RecordA = {
Name: string
// ...
}
type RecordB = {
Name: string
// ...
}
val getTheHandler: (name: string) -> (() -> ())
let handleA (record: RecordA) =
(getTheHandler record.Name) ()
let handleB (record: RecordB) =
(getTheHandler record.Name) ()
I'm wondering if it is possible to write some generic function that would let me simplify/refactor the getTheHandler record.Name. In trying to refactor that snippet the compiler wants to choose one record type of the other.
So trying this, I get a compiler error:
let shorter (record: 'T) =
(getTheHandler record.Name) ()
// later:
shorter myRecordA // FS0001: This expression was expected to have type RecordB but here has type RecordA
Is this possible? Is the only way to make this work to add a member function to each record type?
Yes, it is possible with SRTP - see here: Partial anonymous record in F#
Here's an example using your use case:
let getTheHandler (name: string) () = printfn $"{name}"
let inline handle (r: ^T) =
(^T : (member Name: string) r)
let ra: RecordA = { Name = "hello" }
let rb: RecordB = { Name = "world" }
handle ra // "hello"
handle rb // "world"
I'd also say though, a little repetition isn't that bad. SRTPs can be wonderful, but can lead down a path of getting way too happy with abstraction and sometimes compile-time slow downs. Using it judiciously like this isn't that bad though.
Just for the record, you can also solve this problem by using ordinary object-oriented interfaces. This is something that works quite well with functional design in F# and it is quite clean. There is some more work involved in explicitly implementing the interfaces, but the up side is that you end up with more clear explicit code (and the interface can model the intention better than just a member name):
To define and implement an interface:
type INamed =
abstract Name : string
type RecordA =
{ Name: string }
interface INamed with
member x.Name = x.Name
type RecordB =
{ Name: string }
interface INamed with
member x.Name = x.Name
To use this:
let getTheHandler (name:string) =
fun () -> printfn "Hi %s" name
let handle (record: INamed) =
(getTheHandler record.Name) ()
You also can solve this by using a higher-order function. By doing the selection through a function. It will become generic.
type RecordA = {
Name: string
}
type RecordB = {
Name: string
}
let getTheHandler name = printfn $"{name}"
let handle chooser record =
fun () -> getTheHandler (chooser record)
let ra : RecordA = {Name="Hello"}
let rb : RecordB = {Name="World"}
let name1 = ra |> handle (fun r -> r.Name)
let name2 = rb |> handle (fun r -> r.Name)
name1 ()
name2 ()

How to pass the same mutable Peekable to different functions in Rust

I want to write a parser.
It seems practical to me to have a mutable Iterator that I can pass around to different parser functions.
I've tried to illustrated a simplified approach, which compiles but is not ideal yet.
fn main() {
let tokens = vec!["fIrSt".to_string(), "SeConD".to_string(), "tHiRd".to_string(), "FoUrTh".to_string()];
let parsed = parse_input(tokens);
println!("{}", parsed);
}
fn parse_input(tokens: Vec<String>) -> String {
let mut tokens_iter = tokens.iter();
let upps = parse_upper(&mut tokens_iter);
let lowers = parse_lower(&mut tokens_iter);
upps + &lowers
}
fn parse_upper(tokens_iter: &mut Iterator<Item=&String>) -> String {
let mut result = String::new();
let token_1 = tokens_iter.next().unwrap().to_uppercase();
let token_2 = tokens_iter.next().unwrap().to_uppercase();
result.push_str(&token_1);
result.push_str(&token_2);
result
}
fn parse_lower(tokens_iter: &mut Iterator<Item=&String>) -> String {
let mut result = String::new();
let token_1 = tokens_iter.next().unwrap().to_lowercase();
let token_2 = tokens_iter.next().unwrap().to_lowercase();
result.push_str(&token_1);
result.push_str(&token_2);
result
}
How the example works:
Let's say I have some input, that has already been tokenized. Here it is represented by the tokens vector (Vec<String>).
Inside the outer parse_input function, the Vec gets transformed into an Iterator and then passed into different, specific parser functions. Here: parse_upper and parse_lower. In real life those could be "parse_if_statement" or "parse_while_loop" but which part of the Iterator gets worked on is not relevant for the question.
What is relevant is, that every call to next advances the cursor on the Iterator. So that every function consumes the pieces it needs.
This example compiles and gives the output: FIRSTSECONDthirdfourth
I would like to be able to peek() into the Iterator, before I pass it to a function. This is necessary to determine which function should actually be called. But everything I have tried with using a Peekable instead of an Iterator resulted in total lifetime and borrow chaos.
Any suggestions on how to pass a Peekable instead of an Iterator in this case?
Maybe using a Peekable as function parameter is a bad idea in the first place. Or maybe my Iterator approach is already wrong. All suggestions/hints are welcome.

F# Discriminated Union Type Issue

I'm having a problem getting my DU working as expected. I've defined a new DU which either has a result of type <'a> or any Exception derived from System.Exception
open System
// New exceptions.
type MyException(msg : string) = inherit Exception(msg)
type MyOtherException(msg : string) = inherit MyException(msg)
// DU to store result or an exception.
type TryResult<'a, 't> =
| Result of 'a
| Error of 't :> Exception
//This is fine.
let result = Result "Test"
// This works, doing it in 2 steps
let ex = new MyOtherException("Some Error")
let result2 = Error ex
// This doesn't work. Gives "Value Restriction" error.
let result3 = Error (new MyOtherException("Some Error"))
I can't understand why it is allowing me to create an "Error" if I do it in 2 steps, but when i'm doing the same thing on a single line, I get a Value Restriction error.
What am i missing?
Thanks
UPDATE
Looking at the post by #kvb, adding type information each time I need to create an Error seemed a bit verbose, so I wrapped it up into an additional method which creates an Error and is a bit more succinct.
// New function to return a Result
let asResult res : TryResult<_,Exception> = Result res
// New function to return an Error
let asError (err : Exception) : TryResult<unit,_> = Error(err)
// This works (as before)
let myResult = Result 100
// This also is fine..
let myResult2 = asResult 100
// Using 'asError' now works and doesn't require any explicit type information here.
let myError = asError (new MyException("Some Error"))
I'm not sure if specifying an Error with 'unit' will have any consequences I haven't foreseen yet.
TryResult<unit,_> = Error(err)
Consider this slight variation:
type MyOtherException(msg : string) =
inherit MyException(msg)
do printfn "%s" msg
let ex = new MyOtherException("Some Error") // clearly, side effect occurs here
let result2 = Error ex // no side effect here, but generalized value
let intResults = [Result 1; result2]
let stringResults = [Result "one"; result2] // can use result2 at either type, since it's a generalized value
let result3 = Error (MyOtherException("Some Error")) // result would be of type TryResult<'a, MyOtherException> for any 'a
// In some other module in a different compilation unit
let intResults2 = [Result 1; result3] // why would side effect happen here? just using a generic value...
let stringResults2 = [Result "one"; result3] // likewise here...
The issue is that it looks like result3 is a value, but the .NET type system doesn't support generic values, it only supports values of concrete types. Therefore, the MyOtherException constructor needs to be called each time result3 is used; however, this would result in any side effects occurring more than once, which would be surprising. As Ringil suggests, you can work around this by telling the compiler to treat the expression as a value anyway:
[<GeneralizableValue>]
let result3<'a> : TryResult<'a,_> = Error(new MyOtherException("Some Error"))
This is fine as long as the constructor doesn't have side effects.
You can do:
let result3<'a> = Error (new MyOtherException("Some Error"))
EDIT:
As for why you can't do it in one step, first note that this results in the same error:
let result4 = Result (new MyOtherException("Some Error"))
As does this:
let result4 = Result ([|1;|])
But that this works:
let result4 = Result ([1;])
What's similar about Exception and Arrays, but not Lists? It's their mutability. The value restriction will bother you when you try to do make a TryResult with a type that is mutable in a single step.
Now as for why the two step process solves this, it's because the constructor make the whole function not generalizable because you're applying a function to the constructor. But splitting it into two steps solves that. It is similar to Case 2 here on MSDN.
You can read more about it at the above MSDN article and the why this happens in this more indepth blog post.

F# Discriminated Unions access values

I have a application which runs as a server, dose some calculations and returns a value. I have created a discriminated union type of MessageType so I can have different types of messages passed between applications.
The MessageType is made up of an ExchangeMessage of type ExchangeFrame. The question I have is how to access the values of ExchangeFrame from the MessageType.
The code might explain it better
[<CLIMutable>]
type ExchangeFrame =
{
FrameType: FrameType
Amount: double;
ConvertTo: Currency
ConvertFrom: Currency
}
type MessageType = ExchangeMessage of ExchangeFrame
let server () =
use context = new Context()
// socket to talk to clients
use responder = context |> Context.rep
"tcp://*:5555" |> Socket.bind responder
Console.WriteLine("Server Running")
while true do
// wait for next request from client
let messageReceived = responder |> Socket.recv |> decode |> deserializeJson<MessageType>
//Do Calculations
let total = doCalculations //MessageReceived.ExchangeMessage.Amount 3.0
// send reply back to client
let message = encode <| total
message |> Socket.send responder
server ()
As the design stands, you can access the exchange frame by (1) pattern matching to extract the frame from the MessageType, and then (2) dotting into the frame to extract a field, like this:
let msgType = // creation
let (ExchangeMessage frame) = msgType
let amount = frame.Amount
But see my comments to the question.

F#: Closures vs. private values

Assuming no further modifications or additions will be made to the following type, is there any advantage to doing this one way vs. the other (apart from the less typing and better readability and efficiency of the second example)?
type MyType<'T> (_initVal : 'T) =
let getSetFns () =
let value = ref _initVal
(fun () -> value.Value), (fun _value -> value := _value)
let getVal, setVal = getSetFns ()
member this.Value with get () = getVal () and set _value = setVal _value
... or...
type MyType<'T> (_initVal : 'T) =
let value = ref _initVal
member this.Value with get () = value.Value and set _value = value := _value
The second one is shorter, so I'd go for that. You may want to consider using let mutable rather than a reference cell, it will be slightly more performant (though it's unlikely you'll notice much difference).
To give a little more context, using closures to hide values, as you do in the first case, is a good technique, but here the value is already hidden, so why bother hiding it again ?

Resources