Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there default parameter in F#?

Tags:

f#

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:

  1. 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?

  2. 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?

like image 425
Nick Avatar asked Jun 16 '15 13:06

Nick


People also ask

Which function Cannot have default parameters?

Constructors cannot have default parameters.

What is the default value of parameter method of function?

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.

Does C allow default parameters?

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.

Can all the parameters of a function can be default parameters?

C. All the parameters of a function can be default parameters.


1 Answers

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
like image 167
Daniel Avatar answered Sep 29 '22 13:09

Daniel