You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用hmatrix实现Haskell向量的高效逐元素数学函数运算

Efficient Element-Wise Operations in hmatrix (Like NumPy)

Absolutely! hmatrix is built specifically for high-performance numerical computing in Haskell, and it has exactly the element-wise vector operations you’re craving—no slow recursive list processing needed.

How to Replicate NumPy-Style Element-Wise Math

hmatrix’s Vector type (from the Numeric.LinearAlgebra module) plays nicely with Haskell’s standard numeric type classes, and it offers optimized component-wise operations that mirror NumPy’s behavior perfectly.

For your sigmoid function example, you can write it almost identically to how you would in NumPy:

import Numeric.LinearAlgebra

sigmoid :: Vector Float -> Vector Float
sigmoid z = 1 / (1 + exp (-z))

This works because:

  • Operators like +, -, *, / act element-wise on vectors (just like in NumPy)
  • Standard floating-point functions such as exp, log, sqrt, sin, and cos are automatically lifted to operate element-wise on vectors (thanks to hmatrix’s Floating instance for Vector)

Applying Custom Element-Wise Functions

If you need to use a custom function that isn’t part of the standard numeric type classes, reach for cmap (short for "component-wise map"). It efficiently applies any scalar function to every element of the vector:

-- Example: Element-wise squaring
squareVec :: Vector Float -> Vector Float
squareVec = cmap (^2)

-- Another example: Custom thresholding function
threshold :: Float -> Vector Float -> Vector Float
threshold cutoff = cmap (\x -> if x > cutoff then 1 else 0)

Why This Beats List Recursion

Your original list-based sigmoid relies on pure Haskell recursion, which doesn’t leverage low-level optimizations. hmatrix, by contrast, uses battle-tested BLAS/LAPACK libraries under the hood—these are highly optimized numerical libraries written in C/Fortran, so they’ll handle large vectors far more efficiently than list operations ever could.

Quick Setup Tip

Make sure hmatrix is added to your project dependencies. For a Stack project, add this to your package.yaml:

dependencies:
  - hmatrix >= 0.20

内容的提问来源于stack exchange,提问作者mahmoud fathy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:09:20