Split string by string in F# - f#

In C# I could go like
data.Split(new string[] { "splitHere" }, StringSplitOptions.None);
I can't seem to get the same to work in F# or I may simply be doing it wrong (I just recently started to learn F#)
Update
Just to clarify, my best attempt was
data.Split([", "], StringSplitOptions.None)
I'm fairly new to F# and moved from C#, so I make a number of noob errors still.
On the up side, I couldn't find any info when searching for this subject, and now there's at least 1 :)

You can split string by string like this:
open System
let colors = "red, green, blue"
let colorsArray = colors.Split([|", "|], StringSplitOptions.None)
and the result is
val colorsArray : string [] = [|"red"; "green"; "blue"|]

Related

binary deserialization to another type with FSPickler

I have a type:
type T =
{
a: int
b: string
}
and an array of type T called 'myArray'.
and I want to serialize myArray with FSPickler:
FsPickler.CreateBinarySerializer().Pickle myArray
but in the pickle file, the type T is fully qualified and if I relocate it to another app/namespace, then the unpickle fails.
I asked on the FSPickler git but the answer I received is:
Per documentation in http://mbraceproject.github.io/FsPickler/ the serializer is not > designed with version tolerance in mind. That being said, it should be possible to work > around that issue by providing a custom implementation of the ITypeNameConverter interface.
ok, fair enough.
However, the documentation is providing examples clearly written by someone that knows picklers in general and geared toward other people that know picklers as well.
Can anyone post an example where I could make a custom serializer / deserializer for this basic case? From the docs, I see all the odd cases explained with the assumption that the reader knows how to make a basic serializer with FSPickler.
Or, maybe I missed something terribly obvious in the doc and I'd gladly recognize it if I saw it :)
The doc is here: https://mbraceproject.github.io/FsPickler/tutorial.html
and, for context, I'm going through 24 GB of data (with a type more complex than in this example obviously), so SPEED is everything and FSPickler seems quite fast.
There doesn't seem to be any documentation on this at all, but I managed to hack together something that works. The trick I found is to use a very simple converter that always uses the same type name, like this:
let converter =
{
new ITypeNameConverter with
member this.OfSerializedType(typeInfo) =
{ typeInfo with Name = "dummy" } // always use dummy type name
member this.ToDeserializedType(typeInfo) =
typeInfo
}
We can then pickle an array of Ts like this:
type T =
{
a: int
b: string
}
let tArray =
[|
{ a = 1; b = "one" }
{ a = 2; b = "two" }
{ a = 3; b = "three" }
|]
let serializer = FsPickler.CreateBinarySerializer(typeConverter = converter)
let bytes = serializer.Pickle(tArray)
And then we can unpickle it to an array of a different type that has the same structure ("duck typing"):
type U =
{
a: int
b: string
}
let uArray = serializer.UnPickle<U[]>(bytes)
I have no idea if this is the "right" way to do it. I found that ITypeNameConverter didn't behave like I expected. In particular, it seems that OfSerializedType is called during both pickling and unpickling, while ToDeserializedType isn't called at all. Maybe I'm missing something important.

java swagger 3 annotations #ExampleObject from jsonfile

I'm documention one of my api with multiple examples like this:
#Operation(summary = "Create new")
#PostMapping("")
public ResponseEntity<Object> createOne(
#Parameter(description = "MyDto")
#io.swagger.v3.oas.annotations.parameters.RequestBody(
content = #Content(examples = {
#ExampleObject(name = "one", value = EXAMPLE_ONE),
#ExampleObject(name = "two", value = EXAMPLE_TWO),
#ExampleObject(name = "three", value = EXAMPLE_THREE)}
))
#RequestBody MyDTO body
) {
...
}
This works fine, though EXAMPLE_ONE is a string value. This is pretty unclear as you can see from the example below
private static final String EXAMPLE_ONE = "{\"glossary\":{\"title\":\"example glossary\",\"GlossDiv\":{\"title\":\"S\",\"GlossList\":{\"GlossEntry\":{\"ID\":\"SGML\",\"SortAs\":\"SGML\",\"GlossTerm\":\"Standard Generalized Markup Language\",\"Acronym\":\"SGML\",\"Abbrev\":\"ISO 8879:1986\",\"GlossDef\":{\"para\":\"A meta-markup language, used to create markup languages such as DocBook.\",\"GlossSeeAlso\":[\"GML\",\"XML\"]},\"GlossSee\":\"markup\"}}}}}";
I looking for a better way to provide the example. A json file would be nice, but I couldn't find anything about that.
You can use externalValue instead of value. See here
Use java text-block instead of normal quoted string
e.g. putting triple double (""")
see https://www.baeldung.com/java-text-blocks

Can't serialize records, in F#, with json.net

A very basic example:
type private test =
{
a : string
b : string list
}
let t = { a = "hello"; b = ["1"; "2"] }
let s = JsonConvert.SerializeObject(t)
This will produce an empty string.
I have seen that json.net supports F# and that there are a lot of posts related to enum types, etc but I'm not there yet: I'm trying to serialize something very simple.
Many posts point toward another json serializer project, called Chiron, but it was updated a year ago and they're still like:
We’re working on Guides and reference content for working with Chiron, so keep an eye on the Updates
Is there something obvious I haven't seen?
So ideally, working with json.net would be better, especially since I'm used to it in C#
The issue seems to be that Json.Net only serializes public fields of F# records. When you mark the record as private, all its fields also become private and those are ignored. The following works as expected for me:
type test =
{
a : string
b : string list
}
let t = { a = "hello"; b = ["1"; "2"] }
let s = JsonConvert.SerializeObject(t)
This produces the expected JSON:
{"a":"hello","b":["1","2"]}

Wrong language code swift

I set the language of the simulator to French. To check the language code, I used a couple of solutions:
let lang = NSLocale.autoupdatingCurrent.languageCode
print(lang)
let pre = Locale.preferredLanguages[0]
print(pre)
The result are:
Optional("en")
fr-US
What I expected to get is:
fr
How can I achieve that?
Try below code,
let requiredString = pre.components(separatedBy: "-").first ?? pre //fr
/*if pre.contains("-"), then requiredString = before("-") else requiredString = pre*/
print(Locale.components(fromIdentifier: Locale.preferredLanguages[0])["kCFLocaleLanguageCodeKey"]!)
this will print language code only.
If you want the Language instead of the Language_Region, then I suggest to take the sub string before the _ from the string to neglect the Region.
(If the string contains no _ then take the entire string since it doesn't contain the region in it)

Turn a string into a variable

Hello I have a for in loop where elements is the variable being changed and in this case "elements" is a string but there is a corresponding variable out side of the for in loop that has the same name as the string called elements. So what I mean is out side there is a Var time = [some,text,words] and theres a for in loop that calls a STRING named "time" and I would like to know how to convert the string in the for in loop into the variable by some how taking off the "'s (not that simple I know) without specifically saying "time"(the variable) but instead converting the "elements"(which is the string 'time') string into the variable. I hope I was clear enough if I'm not making sense I'll try again.
You cannot refer to local variables dynamically by their names in Swift. This would break a lot of compiler optimizations as well as type safety if you could.
You can refer to object properties by their names if the class conforms to key-value coding. For example:
class X : NSObject {
let time = ["some", "text", "words"]
func readWordsFromProp(name: String) -> String {
guard let list = self.valueForKey(name) as? [String] else {
return ""
}
var result = ""
for word in list {
result += word
}
return result
}
}
let x = X()
print(x.readWordsFromProp("time"))
In general, there are better ways to do things in Swift using closures that don't rely on fragile name-matching. But KVC can be a very powerful tool

Resources