F# Chaining functions that return tuple

Viewed 89

I am new to F# and am trying to chain functions to make a Higher Order Function.

A simplified example is

init returns a tuple

validate accepts a tuple and returns bool

    let init : string * string =
        ("1", "2")

    let validate ((a: string), (b: string)) : bool =
        a.Equals(b)

    let test = init >> validate

ERROR

This expression was expected to have type 'a -> 'b' but here has type 'string * string'

2 Answers

As the answer for Piotr explains, you are getting an error because you have a value and a function. To compose those, you can turn init into a function, but you do not really need to use composition in this case.

If you want to pass a value as an argument to a function, it is typically much simpler to just pass it as an argument:

let res = validate init

Alternatively, if you have a number of functions you want to apply to your input in a sequence, you can do this using the piping operator:

let res = init |> validate

Function composition using >> is a nice functional trick, but I think it is actually much less common in standard F# code than most people think. I use |> all the time, but >> only rarely.

You can only compose functions using the >> combinator. Your first assignment is not a function - it is a binding to a value - your tuple. You can convert it to a function just by adding empty parameter list () (unit) parameter like this:

let init() : string * string =
    ("1", "2")

let validate ((a: string), (b: string)) : bool =
    a.Equals(b)

let test = init >> validate

let res = test()

Related