Partial application with changing of return type

Viewed 62

I have a function to read a byte from an array:

let readByte array address =   (* []<byte> -> int -> byte *)
    (* ... *)

In an other function where I use this function very often, I'd like to do partial application:

let myOtherFunction array =
    let readByteAsInt = readByte array
    (* ... *)
    let x = readByteAsInt address

Basically this works. In my example x is now of type byte but I would need it as an int. In this simple example I could cast the return value when assigning to x but as I said, I use readByteAsInt very often and I don't want to do the cast on every call.

I have tried

let readByteAsInt = int (readByte array)

and

let readByteAsInt = readByte array |> int

but both result in an error when calling readByteAsInt:

FS0003: This value is not a function and cannot be applied

How can I change the return type of the partial application?

Changing the signature of readByte to return an int is not an option as I do need byte elsewhere.

2 Answers

readByte array is a function, and int is another function; you want to compose them so that the output of readByte array becomes the input of int. You can write readByte array >> int - note that it's >> for composition, instead of |> for application.

Like @kaya3 mentioned, you can use function composition with (<<) or (>>). But even without function application or composition, you could just create another function directly with a parameter instead.

let readByteAsInt pos = int (readByte array pos)
let readByteAsInt pos = readByte array pos |> int

Or the function compositon way

let readByteAsInt = int << readByte array
let readByteAsInt = readByte array >> int

Keep in mind, that function composition, does not always work in F# when the function has a generic input, then you must define a function with arguments explicitly.

Related