Search code examples
functional-programmingf#

Confused about F# method signature syntax


I am supposed to write a small program in F# for a uni assignment. One of the exercises says to create a filter method with this signature: filter : ('a -> bool) -> list<'a> -> list<'a>. But I am struggling to properly interpret this syntax. The docs say the syntax for creating a method is let [inline] function-name parameter-list [ : return-type ] = function-body. But how does my example fit into this? Is it a function which takes no parameters but returns three values?

The function should filter a list given a predicate which is simple enough, but if it doesn't take any parameters, how should I pass a predicate and list? I am sure I'm missing something major because I can't wrap my head around it.


Solution

  • The documentation you may be referring to tells you how to implement a function. The signature you've been given, however, is the desired function's type. F# types are documented here: https://learn.microsoft.com/dotnet/fsharp/language-reference/fsharp-types

    Specifically, the documentation says that in its simplest form, a function has the type parameter-type1 -> return-type, but when it has more parameters, it generally takes the form parameter-type1 -> parameter-type2 -> ... -> return-type.

    In F#, functions are values, so the desired filter is a value that happens to be a function. The function should take two inputs: ('a -> bool) and list<'a>, and return a value of the type list<'a>.

    One of the inputs is a function in its own right: ('a -> bool).