F# - multiply int by float

f#, functional-programming

Solution

let inline mulBy2 x = (float x) * 2.0

let a = mulBy2 3 // 6.0 : float
let b = mulBy2 2.5 // 5.0 : float
let c = mulBy2 "4" // 8.0 : float

Problem

Probably a silly question, but I just got started with F# and I've got a little problem. Say I have a function like this: ``` let multiplyByTwo x = x * 2 ``` When I call this like this: ``` let result = multiplyByTwo 5 ``` Everything is alright, the result is 10. When I call it like this: ``` let result = multiplyByTwo 2.5 ``` I expect to get 5 or 5.0 as a result. The actual result however is this: let result = multiplyByTwo 2.5;; ---------------------------------^^^ stdin(4,28): error FS0001: This expression was expected to have type ``` int ``` but here has type ``` float ``` Because I want this function to be somewhat generic (i.e. accept both floating point numbers and integers), I don't like this. My question of course: how does one solve this?

Original source

Related problems