Yelena
Yelena

Reputation: 433

Function Composition Error

While going through a tutorial on Function Composition, I tried the following:

let prefixFun a b = a + "" + b;;
let exclaim s = s + "!";;
let bigHello = prefixFun >> exclaim;;

But the definition for bigHello returns the following type mismatch error

let bigHello = prefixFun >> exclaim;;
----------------------------^^^^^^^

stdin(28,29): error FS0001: Type mismatch. Expecting a
'(string -> string) -> 'a'
but given a
    'string -> string'
The type 'string -> string' does not match the type 'string'
  1. What does the error mean
  2. As per my understanding, function composition requires return type of first function to be the same as parameter of the second, which I think is true here, since prefixFun returns string and exclaim expects string.

Could you help me understand and resolve the problem.

Thanks.

Upvotes: 0

Views: 79

Answers (1)

Kevin Li
Kevin Li

Reputation: 231

prefixFun, after applying one argument, does not return a string. It returns a function, with type string -> string due to partial application and function currying.

This is the implementation of >>:

let (>>) f g x = g ( f(x) )

Note that f is applied to only one argument.

I have a feeling that what you want for bigHello is a function that takes someone's name and adds an exclamation mark afterwards. Here's what you can do with what you have!

let bigHello = prefixFun "Hello " >> exclaim

Note that prefixFun "Hello " has type string -> string, so the rules for function composition are obeyed.

Upvotes: 5

Related Questions