I have a delimited string of data, e.g.
a~b~c~d~e~f~g~h~i~j~k~l~...
dog~cat~fish~parrot~mother~father~child~grandparent~...
hello~hi~greetings~yo
I am wanting to load the data into an array/seq of records of type
type myType {
first: string;
second: string;
third: string;
fourth:string;
}
so I'd end up with 3 objects in the array/seq. I've been messing around with for loops to do this, but it feels pretty imperative. How would I achieve this using a functional idiom?
EDIT: I should have clarified that the delimited data could be of variable length although the number of delimited items should always be a multiple of 4. So, with each iteration, I am looking to strip 4 pieces of the input data load them into the type and once all the data has been consumed, return an Array/seq.
EDIT 2: So I ended up with something like this
let createValues(data: string) =
let splitValues(valueString) =
let rec splitData acc = function
| a :: b :: c :: d :: xs -> splitData ({ first=a; second=b; third=c; fourth=d } :: acc) xs
| [] -> acc
| _ -> failwith "uneven data"
splitData [] valueString
splitValues (data.Split [|'~'|] |> Array.toList)
Thx
Your type contains only single characters - assuming the data always consists of single characters the delimiter is unnecessary. Here is one way to map the data into a list of your types, this will only work if the amount of characters in the data is divisible by 4, but will work with variable sized inputs.
let data = "a~b~c~d~e~f~g~h~i~j~k~l~m~n~o~p"
let splitData data =
let rec aux acc = function
| a::b::c::d::xs -> aux ({ first=a; second=b; third=c; fourth=d } :: acc) xs
| [] -> acc
| _ -> failwith "uneven data"
aux [] data
let output = splitData (data.Replace("~","").ToCharArray() |> Array.toList)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With