简体   繁体   中英

Creating a random fractional number in F#

I was trying to create a random fractional number as follows:

type Fraction=
  {
  num: int
  den: int
  }

let makeRandomFraction i =
  let n= fun i -> System.Random(i).Next(-50, 51)
  let d= fun i -> System.Random(i*3).Next(-50, 51)
  {num=n; den=d}

but I am getting an error:

error FS0001: This expression was expected to have type
    'int'
but here has type
    'int -> int'

Could you please explain the error and the correct way of doing the required.

The error is saying that you're passing a function (of type int -> int ) where an int is expected. You can see this more clearly in something like:

let add a b = a + b
let inc x = x + 1

inc add
//  ^^^
// This expression was expected to have type 'int' but has type 'int -> int -> int'

The solution here is just to take out the fun i -> parts. That's the (other) syntax for lambdas, but since your i variable is already in scope there's no need to create a function around it.

Out of curiosity, do you have any requirements on what range and distribution of fractions do you want your function to generate? The way the code is currently written - by composing two random numbers in a range -50 .. 50, you will get a distribution with most numbers being close to zero.

Here is a simple histogram built using the XPlot F# library:

随机数分布

open XPlot.GoogleCharts

type Fraction=
  { num: int
    den: int }

let makeRandomFraction i =
  let n = System.Random(i).Next(-50, 51)
  let d = System.Random(i*3).Next(-50, 51)
  {num=n; den=d}

[ for i in 0 .. 100000 -> let f = makeRandomFraction i in float f.num / float f.den ]
|> Seq.filter (System.Double.IsInfinity >> not)
|> Seq.countBy (fun f -> int f)
|> Chart.Column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM