【问题标题】:Import Module fails - module is not defined and value or constructor not defined导入模块失败 - 模块未定义且值或构造函数未定义
【发布时间】:2021-05-25 09:29:24
【问题描述】:

我想使用文件 BasicFunctions.fs 中模块中的函数。 完成f# hello world tutorial 后,下一步是完成F# Tour

what is the equivalent of import in F#printfn an integer 的问题有点帮助。 value or constructor not defined 的问题似乎与我的情况无关。

尝试 1:更改配置以包含第二个文件

如果我将我的项目配置 myFsharpApp.fsproj 更改为此

  <ItemGroup>
    <Compile Include="BasicFunctions.fs" />
    <Compile Include="Program.fs" />
  </ItemGroup>

我收到错误:FSC : error FS0225: Source file 'C:\dev\fsharp\myFSharpApp\BasicFunctions.fs' could not be found [C:\dev\fsharp\myFSharpApp\myFSharpApp.fsproj]

但文件 BasicFunctions.fs 可以在路径“C:\dev\fsharp\myFSharpApp\BasicFunctions.fs”下找到。所以我不明白为什么找不到它。

尝试 2:将配置更改为:

  <ItemGroup>
    <Compile Include="Program.fs" />
  </ItemGroup>

使用dotnet build 然后返回

  1. 错误 FS0039:命名空间或模块 'BasicFunctions' 不是 定义
  2. 错误 FS0001:类型不匹配。期待一个 ''a -> 'b -> 'c' 但是给定一个 ''a -> unit ' 类型 ''a -> 'b' 不匹配 类型“单位”
  3. 错误 FS0039:未定义值或构造函数“sampleFunction1”。[C:\dev\fsharp\myFSharpApp\myFSharpApp.fsproj]

大部分代码都是从F# Tour 复制而来的。不同之处在于我想从文件BasicFunctions.fs 中导入函数并想打印sampleFunction1 x = x*x + 3 的结果

代码结构如下

// BasicFunctions.fs
module BasicFunctions = 
    let sampleFunction1 x = x*x + 3

// Program.fs
module main =
    open BasicFunctions

// Define a new function to print a name.
let printGreeting name =
    printfn "Hello %s from F#!" name

[<EntryPoint>]
let main argv =
    printfn "%d" BasicFunctions.sampleFunction1 3 // 12 expected
    0 // return an integer exit code

问题

  • 我在导入另一个文件及其函数时做错了什么?
  • sampleFunction1 x = x*x + 3 有什么问题?
  • 假设sampleFunction1 返回值为12 的int,为什么printfn "%d" 12 不起作用?

当前代码状态屏幕

fsproj 的内容

这是myFSharpApp.fsproj的内容

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Program.fs" />
  </ItemGroup>

</Project>

【问题讨论】:

    标签: f#


    【解决方案1】:
    • 顶级模块的定义没有 = 和缩进
    • 什么都没有
    • 空格是函数应用程序,因此为了像正确的优先级一样调用,您需要括号或管道

    所以就变成了下面这样。

    // BasicFunctions.fs
    module BasicFunctions
    
    let sampleFunction1 x = x * x + 3
    
    // Program.fs
    open BasicFunctions
    
    [<EntryPoint>]
    let main argv =
        sampleFunction1 3 
        |> printfn "%d" 
        0
    

    请注意,您可以跳过打开并直接引用该模块。这两个文件都需要按顺序包含在内。

      <ItemGroup>
        <Compile Include="BasicFunctions.fs" />
        <Compile Include="Program.fs" />
      </ItemGroup>
    

    【讨论】:

    • 我仍然收到错误 - 请查看我上面的附加屏幕,看看我是否遗漏了什么。
    • 你的 fsproj 看起来怎么样?
    • 您需要按照第一次尝试的顺序包含文件
    • 验证文件是否正确命名。 BasicFunctions 在编辑器中而不是 BasicFunctions 中说
    • 这就是原因。我忽略了文件名是BasicFuntions.fs而不是BasicFunctions.fs
    猜你喜欢
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 2017-11-19
    • 2012-03-27
    • 2013-02-07
    • 1970-01-01
    相关资源
    最近更新 更多