编译时出现‘Cannot unify 't₂' with type 'f32'’错误的原因及解决方法
Ah, I see the issue here—your problem isn’t actually about type matching for x - 1.0, it’s a misunderstanding of Futhark’s operator semantics!
The error message is confusing because it’s pointing to the type conflict caused by the ^ operator, not the subtraction. In Futhark, ^ does not mean exponentiation—it’s reserved for integer bitwise XOR operations, which is why the compiler is insisting that the operands be integer types (i8, i16, etc.) instead of your f32 values.
To fix this, you need to replace the ^ with a valid way to calculate squares for f32 values. Here are two straightforward solutions:
1. Use multiplication (simplest for squaring)
This is the most efficient and readable approach for squaring numbers:
let hit_register (x : f32) (y : f32) : bool = let dx = x - 1.0f32 let dy = y - 1.0f32 dx * dx + dy * dy <= 1.0f32
I’ve explicitly used 1.0f32 to avoid any type inference ambiguity, but even 1.0 would work here since Futhark can infer it matches the f32 type of x and y.
2. Use the standard library power function
If you ever need to calculate exponents other than 2, Futhark provides type-specific power functions like f32.powf:
let hit_register (x : f32) (y : f32) : bool = f32.powf (x - 1.0f32) 2.0f32 + f32.powf (y - 1.0f32) 2.0f32 <= 1.0f32
This function takes two f32 arguments (the base and the exponent) and returns the result as an f32, which aligns perfectly with your use case.
The reason your earlier attempts (changing input types, adding 1.0f32) didn’t fix the error is that the root cause was always the misused ^ operator. Once you replace that with a valid floating-point operation, the type issues will disappear entirely.
内容的提问来源于stack exchange,提问作者Jacob J Nilsson

