'In F#, is it possible to create a type whose instances cannot be passed to ignore?

In F#, is it possible to create a type whose instances cannot be passed to ignore?

type CannotIgnore = | CannotIgnore

let x = CannotIgnore

x |> ignore // Compile-time error
f#


Solution 1:[1]

Its a slightly odd question, even if you could stop people passing it to ignore, they can still just do nothing with it.

The only thing I can add is if you write your API to take a function to handle the resulting value, then you can force the caller to at least write some code it handle it, though they are completely free to do nothing with it, e.g.

type CannotIgnore = CannotIgnore

module Foo = 
    let notAllowedToIgnoreResult (f : CannotIgnore -> 'a) : 'a = 
        let x = CannotIgnore // do the stuff that your function needs to do
        f x

the any client calling this function is forced to write some code to handle the 'return' value

let z = notAllowedToIgnoreResult (fun cannotIgnore -> printfn "I didnt ignore it, I had no choice")

Solution 2:[2]

There's no way to do this without redefining ignore. The best I can come up with is something like this:

[<NoEquality; NoComparison>]
type CannotIgnore = CannotIgnore

let inline ignore< ^t when ^t : equality> (x : ^t) = ()

ignore 3              // Ok
ignore CannotIgnore   // Error: The type 'CannotIgnore' does not support the 'equality' constraint

Of course, this will result in a compiler error for any type that lacks equality, not just CannotIgnore

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2