在 F# 中声明返回 2DArray 的函数的语法

发布于 2024-12-19 14:35:24 字数 415 浏览 1 评论 0原文

我需要在 F# 中声明一个函数,它接受 2 个参数(行、列)并返回 Option 的二维数组(将所有元素初始化为无),但我不知道正确的语法。我尝试过类似的操作:

type T = 
  {
   ....//my type
  }

let create2DArrayOfT (row : int , col: int) Array2D<Option<T>> = Array2D.init<Option<T>> 10 10 (fun -> None)

上面的签名在指定返回类型时是错误的。 所以我有两个问题:

  1. 将返回类型指定为二维数组的正确签名是什么?
  2. 我尝试对数组的元素使用 Option ,因为我希望它允许某些位置为空。这合理吗?

I need to declare a function in F# that takes 2 parameters (row, col) and return an 2-dimensional array of Option (intitializing all elements to be none), but I don't know the right syntax. I've tried something like:

type T = 
  {
   ....//my type
  }

let create2DArrayOfT (row : int , col: int) Array2D<Option<T>> = Array2D.init<Option<T>> 10 10 (fun -> None)

the signature above is wrong in specifing the return type.
So I have 2 questions:

  1. What's the right signature for specifying the return type as a 2-dimensional array?
  2. I've tought to use Option for the elements of my array because I want it to allow some locations to be empty. Is this reasonable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深爱不及久伴 2024-12-26 14:35:24

二维数组的类型在 F# 中写作 'a [,]。下次,您可以使用 F# 交互方式通过查看 Array2D 模块中的函数类型来找到这一点:

> Array2D.create;;
val it : (int -> int -> 'a -> 'a [,]) = <fun:clo@4>

The type of a 2D array is written 'a [,] in F#. Next time, you can find this out using F# interactive by looking at the type of the functions in the Array2D module:

> Array2D.create;;
val it : (int -> int -> 'a -> 'a [,]) = <fun:clo@4>
还不是爱你 2024-12-26 14:35:24

您不需要指定返回类型,因为它将通过类型推断推导出来。
只需使用:

type T = {Name : string}
let create2DArrayOfT (row : int , col: int) = Array2D.init<Option<T>> 10 10 (fun _ _ -> None)

更新:

如果您想指定返回类型,请使用:

let create2DArrayOfT (row : int , col: int) : Option<T> [,] = Array2D.init<Option<T>> 10 10 (fun _ _ -> None)

You don't need to specify return type as that will be deduced by type inference.
Just use:

type T = {Name : string}
let create2DArrayOfT (row : int , col: int) = Array2D.init<Option<T>> 10 10 (fun _ _ -> None)

UPDATE:

If you want specify return type use:

let create2DArrayOfT (row : int , col: int) : Option<T> [,] = Array2D.init<Option<T>> 10 10 (fun _ _ -> None)
菊凝晚露 2024-12-26 14:35:24
let create2DArrayOfT<'T> (row : int , col: int) : 'T option [,] = Array2D.init<'T option> row col (fun _ _ -> None)

注释省略

let create2DArrayOfT<'T> (row, col) = Array2D.init<'T option> row col (fun _ _ ->None)

用法:

let a = create2DArrayOfT<T>(2,3)
let create2DArrayOfT<'T> (row : int , col: int) : 'T option [,] = Array2D.init<'T option> row col (fun _ _ -> None)

anotation omission

let create2DArrayOfT<'T> (row, col) = Array2D.init<'T option> row col (fun _ _ ->None)

usage:

let a = create2DArrayOfT<T>(2,3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文