I have a record type which occurs quite often in a nested complex data structure. Because the record type has an automatically generated ToString the ToString of my bigger structure becomes way to confusing and I do not care for the string representation of my record.
So I want to have an empty string as representation for my record. Overriding ToString seems to not do anything, using StructuredFormatDisplay does not work with empty strings since it requires an input of the form "Text {Field} Text". Right now I have
[<StructuredFormatDisplay("{}")>]
type MyRecord
{ 5 fields... }
override __.ToString () = ""
But this results in The method MyRecord.ToString could not be found.
So what is the correct way to not have a string representation for a record type?
The comments all provide correct information about how to achieve your goal. Pulling it all together, here's what I would do in a real-world scenario where I wanted a record type to always have the empty string as its string representation:
open System
[<StructuredFormatDisplay("{StringDisplay}")>]
type MyRecord =
{
A: int
B: string
C: decimal
D: DateTime
E: Guid
}
member __.StringDisplay = String.Empty
override this.ToString () = this.StringDisplay
This way, regardless of what technique is used to print the record, or if its ToString method is used by an external caller, the representation will always be the same:
let record = {A = 3; B = "Test"; C = 5.6M; D = DateTime.Now; E = Guid.NewGuid()}
printfn "Structured Format Display: %A" record
printfn "Implicit ToString Call: %O" record
printfn "Explicit ToString Call: %s" <| record.ToString()
This prints:
Structured Format Display:
Implicit ToString Call:
Explicit ToString Call:
One thing to keep in mind is that this will even override the way the record is displayed by F# interactive. Meaning, the record evaluation itself now shows up as:
val record : MyRecord =
Related
Let's consider this code:
type TransactionTypes =
| TransactionType1
| TransactionType2
type Test() =
let mutable lastTransactionType1 = DateTime.MinValue
let mutable lastTransactionType2 = DateTime.MinValue
let getLastTransaction transaction =
match transaction with
| TransactionType1 -> lastTransactionType1
| TransactionType2 -> lastTransactionType2
let updateLastTransaction transaction =
match transaction with
| TransactionType1 -> lastTransactionType1 <- DateTime.UtcNow
| TransactionType2 -> lastTransactionType2 <- DateTime.UtcNow
Now (with the understanding that I'm still learning F#), I would like to clarify a couple things:
Something like:
let a = DateTime.Now
does a permanent binding, so 'a' will always be the same time on subsequent uses.
But, my understanding is that if there is a parameter, like:
let a anyParameter = DateTime.Now
will be re-evaluated every time due to the presence of the parameter. Is that correct?
In the code above, the two let statements (getLastTransaction and updateLastTransaction) are private to the type (Test)
I could also have implemented them as:
member private this.getLastTransaction = ...
member private this.updateLastTransaction = ...
Is there any reason, for private functions to prefer let vs. member private this?
"let mutable" already implies the this. so the fields are accessible by both forms.
So, what is the advantage of one form vs. the other?
When you are working with members, F# inherits a lot of things from the .NET object model. A .NET object can have a couple of different things:
Fields - those are storing a value (just like fields of a record). They can be mutable or immutable.
Methods - those can be invoked with zero or more arguments (like functions)
Properties - those have no arguments (like fields); they can be read or written, but when this happens, some code is invoked. A property is basically a pair of getter and setter methods.
In F#, some of this is less visible. However, let corresponds to a field and member with arguments corresponds to a method. Your tricky case is a member without arguments. For example:
type A() =
member x.Foo = printfn "Hi"; 42
Will Hi be printed only once, or will it be printed each time you access Foo? To answer, it's useful to know that Foo is a property with a getter. The above is actually a syntactic sugar for the full version:
type A() =
member x.Foo
with get() = printfn "Hi"; 42
Now you can see that there is a method behind the Foo property! Each time you access Foo, the compiler will generate a call to the get() method, so Hi will be printed repeatedly.
In addition to Tomas' answer:
let mutable lastTransactionType1 = DateTime.MinValue
is equivalent in C# to:
internal DateTime lastTransactionType1 = DateTime.MinValue;
and
member private this.getLastTransaction ...
is the same IL as far as IL is concerned with
let getLastTransaction ...
In equivalent C#, both are
internal DateTime getLastTransactionMember(TransactionTypes transaction)
{
if (transaction.Tag != 1)
{
return lastTransactionType1;
}
return lastTransactionType2;
}
But for using F# in an idiomatic way, you would want to go with let.
There's also a difference in that member does let you use the methods in bindings before their declaration, which might be useful in some cases (read: hacks)
let getType1 = this.getLastTransactionMember TransactionType1 //this compiles
member private this.getLastTransactionMember transaction =
match transaction with
| TransactionType1 -> lastTransactionType1
| TransactionType2 -> lastTransactionType2
One of the benefits of the type system on F# is avoid a null exception... or that was something I believe... because I'm getting a null problem:
[<CLIMutable>]
type Customer = {
[<AutoIncrement>] id:option<int64>
code:string
name:string
}
I'm running a SQL code:
let SqlFTS<'T>(table:string, searchTable:string, query:string) =
use db = openDb()
let sql = sprintf "SELECT * FROM %s WHERE id in (SELECT docid FROM %s WHERE data MATCH %A)" table searchTable query
printfn "%A" sql
db.SqlList<'T>(sql) |> Seq.toArray
testCase "Customers" <|
fun _ ->
let rows = GenData.genCustomers(50)
Customers.insert(rows)
isEqual "Failed to insert" 50L (DB.SqlCount<Customers.Customer>())
//Until here, it works
let c = Customers.byId(1L)
printfn "%A" c
//Customers.byId return me a record with all the properties as NULLS!
//Then c.name is null, and the code above fail.
let rows = Customers.searchCustomers(c.name)
This was very unexpected. Why I can get a record with all values to null?
Let's start with line 1:
[<CLIMutable>]
The docs for CLIMutable state
Adding this attribute to a record type causes it to be compiled to a Common Language Infrastructure (CLI) representation with a default constructor with property getters and setters.
That default constructor means the fields will be initialized to default values. The default value for string is null. That's valid to the CLR and it's valid to C# and VB.NET. You may not be able to call the default ctor from F#, but pretty much anyone else can.
Welcome to interop; it can be a pain.
Designing with Single-Type-Case DUs
given
type DoB = | DoB of System.DateTime
let DoB (dt:DateTime) = // shadow constructor
if(dt.Year>1914) // business defines what a min Date of Birth should be
then Some(DoB dt)
else None
And I see via Answers to wrapping Multi-case DU's you can do the constructor shadowing without an .fsi file very easily.
By Unwrapping I mean let value (EmailAddress e):string = e from the article (which would have to be in the .fsi file or applied to this DoB type would look like
let value (DoB dob):DateTime = dob if we had an .fsi file.
can you do the same somehow for unwrapping that was done with the constructor?
can I somehow define an unwrapper or augmentation of some sort?
If I understand what you mean by unwrapping, you could use an active pattern:
//File1.fs
let (|DoB|) (DoB dt) = dt
//File2.fs
let dob = DoB DateTime.Now //using `DoB` "constructor" function
match dob with
| Some (DoB dt) -> //using `DoB` active pattern
printfn "DOB: %A" dt
| None ->
printfn "Not a DOB"
This works, without shadowing the function of the same name, because active patterns live in a separate naming scope.
This question is in follow up to an earlier question, Preserving Field names across the F#/C# boundary
Because of the current limitation encountered with F# type providers (see the earlier question), I want to map the type-provider-generated list to my own list of records, in which the record is, in part,
type inspection = {
inspectionID : string;
inspectorID : int;
EstablishmentID : string;
EstablishmentName : string; // other members elided
}
I think the way to do this will use Seq.map, but I am not certain. (Recall I am doing a learning exercise.) So here is what I tried:
type restaurantCsv = CsvProvider<"C:\somepath\RestaurantRatings2013.csv",HasHeaders=true>
// which generates a type, but it is an "erased" type, so member names do not propogate
// over to C#.
type RawInspectionData(filename : string) =
member this.allData = restaurantCsv.Load(filename) // works fine
member this.allInspections =
this.allData.Data
|> Seq.map(fun rcrd -> new inspection[{inspectionID = rcrd.InspectionID;}])
and, of course, the complete statement would have the other member names as part of the inspection, here elided for brevity. Someone pointed me to p 43 of F# For Scientists, which is why I thought to use this format with the curly braces. But this yields a syntax error, "Unexpected symbol '{' in expression. Expected ',', ']' or other token."
Hopefully, though, this snippet is adequate to show what I would like to do, create a Generated Type from the Erased Type. How can I accomplish this?
Your code is going in the right direction. When using Seq.map (which is like Select in LINQ), you need to turn a single element of the original sequence into a single element of the new sequence. So the lambda function just needs to create a single instance of the record.
A record is constructed using { Field1 = value1; Field2 = value2; ... } so you need:
type RawInspectionData(filename : string) =
let allData = restaurantCsv.Load(filename) // works fine
member this.allInspections =
allData.Data
|> Seq.map(fun rcrd -> {inspectionID = rcrd.InspectionID})
I also changed allData from a member to a local let definition (which makes it private field of the class). I suppose that your original code new inspection[{...}] tried to create a singleton array with the element - to create an array you'd write [| { Field = value; ... } |] (and the compiler would infer the type of the array for you). But in this case, no arrays are needed.
define a function that has a single parameter of type string which which displayed on console. invoke the function passing it a message. ensure the function ignores any returned value
open System
let NoReturnFunction msg =
Console.WriteLine(string(msg))
NoReturnFunction "Hello World"
I am in a trouble to how to avoid return value of function
In this case there is no work to do because the WriteLine method doesn't return any values. It's a void returning function. In general though the way to ignore a return value in F# is to use the ignore function.
1 + 2 |> ignore
Couple of minor nit picks on the your code sample. The first is you can avoid the cast to string by simply typing the parameter. Second in F# it's more idiomatic to use the printfn function instead of Console.WriteLine
let NoReturnFunction (msg : string) =
printfn "%s" msg
For sake of completeness, you can also let F# infer the parameter type and the return type--like so:
let NoReturnFunction st = printfn "%s" st
This infers the type of s and the return type of NoReturnFunction (unit in this case).