F # phantom in practice

I often have a function with several parameters of the same type, and sometimes use them in the wrong order. As a simple example

let combinePath (path : string) (fileName : string) = ... 

It seems to me that phantom types will be a good way to catch any confusion. But I do not understand how to apply this example only in the F # phantom question.

How do I implement phantom types in this example? What can I call combPath? Or did I miss a simpler solution to the problem?

+6
source share
2 answers

I think the easiest way is to use discriminated associations:

 type Path = Path of string type Fname = Fname of string let combinePath (Path(p)) (Fname(file)) = System.IO.Path.Combine(p, file) 

You could call it that

 combinePath (Path(@"C:\temp")) (Fname("temp.txt")) 
+12
source

I agree with Petr take, but for completeness, note that you can only use phantom types when you have a generic type, to use them so that you cannot do anything with simple string inputs. Instead, you can do something like this:

 type safeString<'a> = { value : string } type Path = class end type FileName = class end let combinePath (path:safeString<Path>) (filename:safeString<FileName>) = ... let myPath : safeString<Path> = { value = "C:\\SomeDir\\" } let myFile : safeString<FileName> = { value = "MyDocument.txt" } // works let combined = combinePath myPath myFile // compile-time failure let combined' = combinePath myFile myPath 
+7
source

Source: https://habr.com/ru/post/976005/


All Articles