Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor a function using "ignore"

Tags:

f#

When should I use "ignore" instead of "()"?

I attempted to write the following:

let log = fun data medium -> ()

I then received the following message:

Lint: 'fun _ -> ()' might be able to be refactored into 'ignore'.

So I updated the declaration to the following:

let log = fun data medium -> ignore

Is there any guidance on why I might use one over the other?

My gut tells me that I should use ignore when executing an actual expression. In this case though, I'm declaring a high-order function.

Are my assumptions accurate?

like image 421
Scott Nimrod Avatar asked Jan 05 '23 17:01

Scott Nimrod


2 Answers

The linter message that you got here is a bit confusing. The ignore function is just a function that takes anything and returns unit:

let ignore = fun x -> ()

Your log function is a bit similar to ignore, but it takes two parameters:

let log = fun data medium -> ()

In F#, this is actually a function that returns another function (currying). You can write this more explicitly by saying:

let log = fun data -> fun medium -> ()

Now, you can see that a part of your function is actually the same thing as ignore. You can write:

let log = fun data -> ignore

This means the same thing as your original function and this is what the linter is suggesting. I would not write the code in this way, because it is less obvious what the code does (it actually takes two arguments) - I guess the linter is looking just for the simple pattern, ignoring the fact that sometimes the refactoring is not all that useful.

like image 86
Tomas Petricek Avatar answered Jan 12 '23 06:01

Tomas Petricek


Never, at least not in the way shown in the question.

Substituting between ignore and () is not meaningful, as they are different concepts:

  • ignore is a generic function with one argument and unit return. Its type is 'T -> unit.
  • () is the only valid value of type unit. It is not a function at all.

Therefore, it's not valid to do the refactor shown in the question. The first version of log takes two curried arguments, while the second version takes three.

What Lint is trying to suggest isn't quite clear. ignore is a function with one argument; it's not obvious how (or why) it should be used to refactor a method that takes two curried arguments. fun _ _ -> () would be an okay and quite readable way to ignore two arguments.

like image 38
Vandroiy Avatar answered Jan 12 '23 04:01

Vandroiy