簡體   English   中英

F#中的“進口”相當於什么

[英]What is the equivalent of “import” in F#

如何從 F# 中的另一個文件導入 function? 就像您在 Python 中import一樣。 我試過open#using ,沒有任何效果。 我查看了官方文檔,但我仍然無法弄清楚如何使用它。

基本上,我想要這樣的東西:

// Log.fs

module Log = 
    let log = 
        printfn "Hello, World"
// Program.fs
open Log

module main = 
    [<EntryPoint>]
    let main argv =
        log // Not working
        0

相當於import的是open

如果我拿你的 pastebin 代碼,它確實有一堆錯誤,如 SharpLab 所示。 這里有幾點需要注意:

  1. F# 喜歡它的代碼訂購。 每個文件都被視為一個單獨的編譯單元,您需要的任何內容只能在以下文件中引用,而不能在前一個文件中引用。
  2. 在單個文件中,您可以使用and創建循環引用,但除此之外,同樣適用:無論您想使用什么類型、值、模塊,它必須已經存在並且在 scope 中。
  3. 您創建了一個對數值,而不是一個對數函數。
  4. 您忘記了module定義后的=符號。

您的原始代碼是這樣的:

// Program.fs
module main
open Log

[<EntryPoint>]
let main argv =
    printfn "Hello"
    log
    0 // return an integer exit code


// Log.fs
module Log

let log =
    printfn "Hello"

這會產生以下錯誤:

錯誤 FS0039:未定義命名空間或模塊“日志”。

你得到這個是因為你有一個open Log ,但是模塊Log還不存在。

錯誤 FS0010:定義中結構化構造的意外開始。 應為“=”或其他標記。

這是關於最后一個let ,它必須縮進。

錯誤 FS0010:實現文件中的此點或之前的不完整結構化構造

同樣的事情,由先前的錯誤引起。

在我更改代碼順序后,適當縮進,將let log更改為let log() ,並添加必要的=符號, 它就可以了,試試看

// Log.fs
module Log =
    let log() =
        printfn "Hello"

// Program.fs
module main = 
    open Log

    [<EntryPoint>]
    let main argv =
        printfn "Hello"
        log()
        0 // return an integer exit code

請注意,在模塊內部,您可以刪除第一級縮進和=符號,但前提是它是該文件中的唯一模塊並且它是項目中的最后一個文件(所以通常我建議不要這樣做,保持簡單,總是縮進並且總是在那里有=符號)。

但只是為了向您展示一個也有效的替代方案:

// Log.fs
module Log =
    let log() =
        printfn "Hello"

open Log

[<EntryPoint>]
let main argv =         // it is the last in the file or prj, this is allowed
    printfn "Hello"
    log()
    0 // return an integer exit code

另請注意,如果將代碼放在不同的文件中,則必須在文件的最頂部添加名稱空間聲明。 通常這將是整個項目的默認命名空間。

這行得通。我在使用您的語法時遇到錯誤(在 VS 2017 Files in libraries or multiple-file applications must begin with a namespace or module declaration. When using a module declaration at the start of a file the '=' sign is not allowed. If this is a top-level module, consider removing the = to resolve this error. Files in libraries or multiple-file applications must begin with a namespace or module declaration. When using a module declaration at the start of a file the '=' sign is not allowed. If this is a top-level module, consider removing the = to resolve this error.

// Log.fs

module Log

let log = 
    printfn "Hello, World"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM