I wrote a program to convert file size from bytes to a human readable format in F#:
let rec sizeFmt num i =
let suffix="B"
let unit = ["";"Ki";"Mi";"Gi";"Ti";"Pi";"Ei";"Zi"]
match abs num with
| x when x < 1024.0 -> printfn "%3.1f %s%s" num unit.[i] suffix
| _ -> sizeFmt (num / 1024.0) (i+1)
let humanReadable n =
sizeFmt (float n) 0
Run example:
> humanReadable 33;;
33.0 B
val it : unit = ()
> humanReadable 323379443;;
308.4 MiB
val it : unit = ()
>
Question:
It would be nice if I can set i=0
as the default value in the
sizeFmt
funciton. I checked the F# documentation, only found that
there's no default parameter. So I have to write a wrapper function
humanReadable
. Is there a better way?
In order to handle both int and float type input like humanReadable 123;;
and humanReadable 123433.33;;
, I have to add a float n
in the wrapper function. The obvious problem is: it is very easy to exceed the max int
size which is 2,147,483,647. I guess there might be a better way, are there?
Constructors cannot have default parameters.
Description. In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help.
There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.
C. All the parameters of a function can be default parameters.
If sizeFmt
is only used by humanReadable
, it makes sense to make it an inner function. That avoids the 'parameter default' issue.
Also, marking the outer function inline
causes it to accept any type of n
that supports explicit conversion to float
.
let inline humanReadable n =
let rec sizeFmt num i =
let suffix="B"
let unit = ["";"Ki";"Mi";"Gi";"Ti";"Pi";"Ei";"Zi"]
match abs num with
| x when x < 1024.0 -> printfn "%3.1f %s%s" num unit.[i] suffix
| _ -> sizeFmt (num / 1024.0) (i+1)
sizeFmt (float n) 0
humanReadable 123 //works
humanReadable 123433.33 //also works
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