c - 在 f# 中编写方法

标签 c f#

我有一个问题:

C中有这样的方法:

inline void ColorSet(int face, int pos,int col)
{
  color[face*9+pos]=col;
}

我尝试用 F# 编写它;

type ColorSet =
    member this.ColorSet (face: int, pos: int, col: int) = 
        color.[face*9+pos] = col

但是我遇到了这样的错误:

The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints...

你能帮我写一下具体的方法吗?

最佳答案

阅读评论,看来您可能正在尝试这样做:

let itemCount = 9
let faceCount = 6

let color : int [] = Array.zeroCreate (faceCount * itemCount)

let setColor face pos col =
    color.[face * itemCount + pos] <- col

有两点需要注意:

  • 不确定类型的对象错误通常可以通过类型注释来解决:通过声明 color: int [] ,指定color必须是整数数组

  • 运算符 =是 F# 中的相等性测试。要分配给可变变量或数组组件,请使用 <- .

用法可能如下所示:

let red = 0xFFFF0000 // Assuming ARGB (machine endianness)
setColor 0 8 red // Set the last component of the first face to red

请注意,这对于 F# 来说是不寻常的风格。我确实使用这样的代码,但前提是已知它对性能至关重要并且编译器无法优化它。通常,您会使用颜色类型,例如System.Drawing.Color 用于兼容性,以及 face 迭代的对象的类型参数。

<小时/>

编辑 您是否将骰子或长方体的 6 个面的颜色交错存储在数组中?以防万一有人感兴趣,我将假设这一点并写出它在更典型的 F# 中的外观。 我不知道这是否相关,但我想添加它不会有什么坏处。

/// A color, represented as an int. Format, from most to least
/// significant byte: alpha, red, green, blue
type Color = Color of int

let black = Color 0xFF000000
let red   = Color 0xFFFF0000

type CubeColors =
    { Top   : Color; Bottom : Color
      Left  : Color; Right  : Color
      Front : Color; Back   : Color }

    /// Creates CubeColors where all faces have the same color
    static member Uniform c =
        { Top=c; Bottom=c; Left=c 
          Right=c; Front=c; Back=c }

// Make an array with nine completely black cubes
let cubes = Array.create 9 (CubeColors.Uniform black)

// Change the top of the second cube to red
cubes.[1] <- { cubes.[1] with Top = red }

这使用单例 discriminated union对于Color类型和 record对于CubeColors类型。与执行低级数组操作相比,这使用起来更安全,而且通常更具可读性。

关于c - 在 f# 中编写方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27637816/

相关文章:

.net - F# 和鸭式打字

.net - 如何在 .NET Core 上直接调用 F# 编译器?

c - Atmega @ 8MHZ 延迟 8 倍到快

c - 指针:表达式不可赋值

F#:如何仅在 Deedle 数据框的某些特定列上运行 fillMissing

f# - 什么时候创建 fsc 一个 init@ 变量?

f# - 在 f# 模式中使用绑定(bind)到标识符的值?

c - 如何获取结构数据的hexdump

c - 从 stdin 读取未知长度的未知行数

c - 如何从命令行运行 Visual Studio 调试器?