F#幻影类型在实践中



我经常有一个函数有多个相同类型的参数,有时会按错误的顺序使用它们。作为一个简单的例子

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

在我看来,幻影类型是捕捉任何混乱的好方法。但我不明白如何在唯一的F#幻影类型问题中应用这个例子。

在本例中,我将如何实现幻影类型?我该如何称呼combinePath?还是我错过了一个更简单的问题解决方案?

我认为最简单的方法是使用有区别的并集:

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

你可以这样称呼它

combinePath (Path(@"C:temp")) (Fname("temp.txt"))

我同意Petr的观点,但为了完整性,请注意,只有在有泛型类型可供使用时,才能使用幻影类型,因此不能对普通string输入执行任何操作。相反,你可以这样做:

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

相关内容

最新更新