I want to separate thousand hundreds from millions? Is there any way to do that?
for example:
int 7770493;
result1 = 7000000;
result2 = 770493;
Related
The answer on Confused about static dictionary in a type, in F# finished with one advice: and just in general: try to use fewer classes and more modules and functions; they're more idiomatic in F# and lead to fewer problems in general
Which is a great point, but my 30 years of OO just don't want to give up classes just yet (although I was fighting against C++ like crazy when we moved away from C...)
so let's take a practical real world object:
type Currency =
{
Ticker: string
Symbol: char
}
and MarginBracket =
{
MinSize: decimal
MaxSize: decimal
Leverage: int
InitialMargin: decimal
MaintenanceMargin: decimal
}
and Instrument =
{
Ticker: string
QuantityTickSize: int
PriceTickSize: int
BaseCurrency: Currency
QuoteCurrency: Currency
MinQuantity: decimal
MaxQuantity: decimal
MaxPriceMultiplier: decimal
MinPriceMultiplier: decimal
MarginBrackets: MarginBracket array
}
// formatting
static member private formatValueNoSign (precision: int) (value: decimal) =
let zeros = String.replicate precision "0"
String.Format($"{{0:#.%s{zeros}}}", value)
static member private formatValueSign (precision: int) (value: decimal) =
let zeros = String.replicate precision "0"
String.Format($"{{0:+#.%s{zeros};-#.%s{zeros}; 0.%s{zeros}}}", value)
member this.BaseSymbol = this.BaseCurrency.Symbol
member this.QuoteSymbol = this.QuoteCurrency.Symbol
member this.QuantityToString (quantity) = $"{this.BaseSymbol}{Instrument.formatValueSign this.QuantityTickSize quantity}"
member this.PriceToString (price) = $"{this.QuoteSymbol}{Instrument.formatValueNoSign this.PriceTickSize price}"
member this.SignedPriceToString (price) = $"{this.QuoteSymbol}{Instrument.formatValueSign this.PriceTickSize price}"
member this.RoundQuantity (quantity: decimal) = Math.Round (quantity, this.QuantityTickSize)
member this.RoundPrice (price : decimal) = Math.Round (price, this.PriceTickSize)
// price deviation allowed from instrument price
member this.LowAllowedPriceDeviation (basePrice: decimal) = this.MinPriceMultiplier * basePrice
member this.HighAllowedPriceDeviation (basePrice: decimal) = this.MaxPriceMultiplier * basePrice
module Instrument =
let private allInstruments = Dictionary<string, Instrument>()
let list () = allInstruments.Values
let register (instrument) = allInstruments.[instrument.Ticker] <- instrument
let exists (ticker: string) = allInstruments.ContainsKey (ticker.ToUpper())
let find (ticker: string) = allInstruments.[ticker.ToUpper()]
In this example, there is an Instrument object with its data and a few helper members and a module which acts as a repository when it's time to find an object by name (a trading ticker in this case, so they're known and formatted, it's not a random string)
I could move the helping member to the module, for example:
member this.LowAllowedPriceDeviation (basePrice: decimal) = this.MinPriceMultiplier * basePrice
could become:
let lowAllowedPriceDeviation basePrice instrument = instrument.MinPriceMultiplier * basePrice
So the object would become simpler and could eventually be turned into a simple storage type without any augmentations.
But I am wondering what are the practical benefits (let's just consider readability, maintainability, etc)?
Also, I don't see how this could be re-structured to not be a class, short of having an 'internal' class in the module and doing all operations through that, but that would just be shifting it.
Your intuition about turning LowAllowedPriceDeviation to a module is correct: it could become a function with the this parameter moved to the end. That is an accepted pattern.
Same goes for all other methods on the Instrument type. And the two private static methods could be come private functions in the module. The exact same approach.
The question "how this could be re-structured to not be a class" confuses me a bit, because this is not actually a class. Instrument is a record, not a class. The fact that you gave it some instance and static methods doesn't make it a class.
And finally (though, technically, this part is opinion-based), regarding "what are the practical benefits" - the answer is "composability". Functions can compose in the way that methods can't.
For example, say you wanted a way to print multiple instruments:
let printAll toString = List.iter (printfn "%s" << toString)
See how it's parametrized with a toString function? That's because I'd like to use it for printing instruments in different ways. For example, I might print their prices:
printAll priceToString (list())
But if PriceToString is a method, I'd have to introduce an anonymous function:
printAll (fun i -> i.PriceToString) (list())
This looks just a little bit more involved than using a function, but in practice it gets very complicated fast. A bigger problem, however, is that this wouldn't even compile because type inference doesn't work on properties (because it can't). In order to get it to compile, you have to add a type annotation, making it even uglier:
printAll (fun (i: Instrument) -> i.PriceToString) (list())
That's just one example of function composability, there are many others. But I'd rather not write a whole blog post on this subject, it's already much longer than I'd like.
I was wondering if I could make an app in which time is display in words instead of conventional numbers. Do you think that there is any package for dart to convert time or numbers to words?
For example
1:30 AM will be One : Thirty AM
Thanks for reading this question. Have a wonderful day.
You can use any of available package to convert from number to words example
package: https://pub.dev/packages/number_to_words
import 'package:number_to_words/number_to_words.dart';
main(){
String input = '1:30 AM';
var s1 = input.split(':');
var s2 = s1[1].split(' ');
String hour = s1[0];
String minute = s2[0];
String hourWord = NumberToWord().convert('en-in',int.parse(hour));
String minuteWord = NumberToWord().convert('en-in',int.parse(minute));
print('$hourWord:$minuteWork ${s2[1]}');
}
I got a couple user IDs I want to send in an array, but can't figure out the correct Swift 3 syntax for creating an array with very long integers. I tried casting, # prefix and using as AnyObject, but that did not work.
let idArray = [10211420262370680, 10211420262370680]
Error: integer literal overflows when stored into int
What is the correct way to create an array with such long integers?
Try this instead:
let idArray: [UInt64] = [10_211_420_262_370_680, ...]
As a back of the envelope calculation, every 10 bits buys you 3 decimal digits. For instance, UInt32 maxes out around 4_000_000_000 and so on.
By the way, the underscores _ above are just syntax sugar for big number literals ;-)
Signed long's array:
let signed64BitIntegerArray: [Int64] = [-10211420262370680, 10211420262370680]
Unsigned long's array:
let unsigned64BitIntegerArray: [UInt64] = [ 10211420262370680, 10211420262370680]
If you need C interop/FFI, use CLong or CUnsignedLong.
In my app, I want to sum two quantities ActiveEnergyBurned and BasalEnergyBurned per day and show it. Is it possible to do this using a single HKQuery? Or do I have to fetch them separately and add them together?
If so, How do I join the results of two query? Any help is appreciated
var startDate = DateTime.Now.Date;
var endDate = startDate.AddDays(1);
var predicate = HKQuery.GetPredicateForSamples((NSDate)startDate,
(NSDate)endDate, HKQueryOptions.None);
HKStatisticsOptions sumOptions = HKStatisticsOptions.CumulativeSum;
HKStatisticsQuery sQuery = new HKStatisticsQuery(qType, predicate,
sumOptions, (hQuery, result, error) => {
HKQuantity sum = result.SumQuantity();
var date = result.EndDate;
var dateTime = DateHelperIOS.NSDateToDateTime(date);
double value = sum.GetDoubleValue(hkUnit);
});
HKHealthStore HStore = new HKHealthStore();
HStore.ExecuteQuery(sQuery);
HealthKit queries, including HKStatisticsQuery can query only one quantity type at a time(*).
You can execute several queries in parallel in the background. This is probably faster than executing the queries sequentially.
(*) There is one exception, HKActivitySummary, that returns several values, but not all you want.
I'm in the process of learning F# - and is currently looking into Units of Measure. I have a simple calculation returning meters per second, and I want to introduce a function converting it to kilometres per hour.
My code looks like this:
[<Measure>] type kg
[<Measure>] type s
[<Measure>] type m
[<Measure>] type km
[<Measure>] type h
let msToKmph(speed : float<m/s>) =
(float speed) * 3.6<km/h>
let gravityOnEarth = 9.81<m/s^2>
let heightOfJump = 3.5<m>
let speedOfImpact = sqrt (2.0 * gravityOnEarth * heightOfJump)
let speedOfImpactKmh = msToKmph(speedOfImpact)
This works - I get 8.28673639 m/s and 29.832251 km/h. What I am unsure of is if this is the best way to express the relationship between different units. Can this be done more elegantly?
For instance, the line doing (float speed) to remove the unit information from the speed parameter, to make the msToKmph return km/h. If I did not remove unit information before doing the calculation, the returned unit would be: km m/(h s)
First, your msToKmph is totally incorrect. Although it returns a correct return value, what it is actually doing, is it just drops the original <m/s> value by converting to a plain, measureless float and then multiplies the measureless value to a 3.6<km/h>.
To better express the relations between UoM's, consider this:
let kmToM = 1000.0<m/km> // relation between kilometers and meters
let hrToSec = 3600.0<s/h> // relation between seconds and hours
let msToKmph(speed : float<m/s>) =
speed / kmToM * hrToSec
Note, all "magic numbers" are encapsulated within UoM converters, hence your formulas remain clean, e.g. they simply operate values and constants, but the UoM are calculated by the compiler.
Update: The philosophy of UoM conversion is that the conversion formulas should be something that has physical sense. The rule of thumb is whether your conversion value presents in reference books. In plain English, 3.6<km/h> from above is useless, but 1000.0<m/km> just says, "there is 1000 m in 1 km", which makes sense.
You can even improve hrToSec like this:
let hrToSec2 = 60.0<s/minute> * 60.0<minute/h>
This will make every value a well-known value found in reference books.
You're right that removing unit information is a bad thing. You should create a few constants with appropriate units for conversion.
let mPerKm = 1000.0<m/km>
let secondPerHour = 3600.0<s/h>
// val msToKmph : float<m/s> -> float<km/h>
let msToKmph(speed : float<m/s>) =
speed / mPerKm * secondPerHour
For km and m, a generic solution is to define a unit prefix k so it works for many UoMs which have kilo as a metric:
[<Measure>] type k
let kilo = 1000.0<1/k>
let secondPerHour = 3600.0<s/h>
// val msToKmph : float<m/s> -> float<k m/h>
let msToKmph(speed : float<m/s>) =
speed / kilo * secondPerHour