Mai*_*tor 5 haskell haskell-linear
这是一个关于风格的简单问题.我一直在用:
import Linear
point = V3 1 2 3
scaled = fmap (* 2) point
Run Code Online (Sandbox Code Playgroud)
要么...
scaled = (* 2) <$> point
Run Code Online (Sandbox Code Playgroud)
这是预期的方式,还是由标量运算符进行适当的乘法?
该linear库导出一个实例Num a => Num (V3 a),所以你实际上可以这样做
> point * 2
V3 2 4 6
Run Code Online (Sandbox Code Playgroud)
如果您使用GHCi,您可以看到它的含义2 :: V3 Int:
> 2 :: V3 Int
V3 2 2 2
Run Code Online (Sandbox Code Playgroud)
因此fromIntegerfor 的实现V3看起来像
fromInteger n = V3 n' n' n' where n' = fromInteger n
Run Code Online (Sandbox Code Playgroud)
这意味着你可以做的事情
> point + 2
V3 3 4 5
> point - 2
V3 (-1) 0 1
> abs point
V3 1 2 3
> signum point
V3 1 1 1
> negate point
V3 (-1) (-2) (-3)
Run Code Online (Sandbox Code Playgroud)
V3也实现Fractional,所以你应该能够使用/和合作.当你的点包含Fractional值.然而,使用的fmap是比较一般,您可以将您V3 Int到V3 String,例如:
> fmap show point
V3 "1" "2" "3"
Run Code Online (Sandbox Code Playgroud)
该fmap函数将允许您将类型的函数a -> b应用于a V3 a以获得V3 b对输出类型没有任何限制(必须如此).使用fmap没有错,它只是不像使用普通算术运算符那样可读.大多数Haskellers在阅读它时都没有任何问题,但它fmap是一个非常通用的工具,可以显示几乎所有类型.