import Control.Monad.ST
import Data.STRef
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
-- what the heck is that s?
new0 :: (MV.Unbox a, Num a) => ST s (MV.STVector s a)
new0 = do
v <- MV.new 10
MV.write v 1 10
MV.write v 2 10
return v
new1 :: (MV.Unbox a) => IO (MV.IOVector a)
new1 = MV.new 10
new2 :: (MV.Unbox a, Num a) => IO (MV.STVector RealWorld a)
new2 = do
v <- MV.new 10 …Run Code Online (Sandbox Code Playgroud) import Data.Typeable(typeOf)
myFunc :: (Show a) => [a] -> [String]
myFunc
| show (typeOf a) == "[Char]" = ...
| otherwise = ..
Run Code Online (Sandbox Code Playgroud)
我使用上面的代码来测试输入是否属于该String类型。这是正确和可以接受的还是有其他更好的方法?
目的是使类型类约束代码更清晰。
type CanThrowDice = (Monad m, MonadIO m, Random a)
throwDice :: CanThrowDice m a => (a, a) -> m a
throwDice (r1, r2) = ...
Run Code Online (Sandbox Code Playgroud)
而不是写:
throwDice :: (Monad m, MonadIO m, Random a) => (a, a) -> m a
throwDice (r1, r2) = ...
Run Code Online (Sandbox Code Playgroud)
我记得在某处看到过这种用法,但不记得了。上面的代码警告我添加一些额外的编译指示,例如ConstraintKinds我无法使其工作。
我可以理解为什么MVector类型(来自vector包)没有实例化Foldable类型类吗?我想人们经常需要迭代向量。我可以freeze它Data.Vector,然后进行迭代。但我讨厌改变这些东西,好像我们对String, Text, Bytestrings 等做得不够。
就我而言,我想打印每个元素。
为什么 ghc 不会抱怨以下函数中的类型僵化?
play :: (Monad m, MonadIO m, Random a) => a -> a -> m a
play r1 r2 = do
randomRIO (r1, r2)
Run Code Online (Sandbox Code Playgroud)
在上述情况下,m实际上是IO。此代码编译。有时,当我在泛型函数中使用具体类型时,ghc 会抱怨我使用的是具体类型。我在这里想念什么吗?
例如,如果我说:
play :: (Monad m, MonadIO m, Random a) => a -> a -> m a
play r1 r2 = do
randomRIO (1, 6::Int)
Run Code Online (Sandbox Code Playgroud)
这次 ghc 抱怨我使用的是刚性类型。困扰我的事情是它IO在某种程度上是一种具体的或刚性的类型,因为它是IO而不是Maybe.
编辑 1: 编译无错误的完整代码:
{-# LANGUAGE ConstraintKinds #-}
module Main where
-- showing how to program …Run Code Online (Sandbox Code Playgroud) 在inline-c包中,有一个调用Haskell 的C 库 GNU Scientific Library 的示例。gsl
solveOde fun x0 f0 xend =
coerce $ solveOdeC (coerce fun) (coerce x0) (coerce f0) (coerce xend)
Run Code Online (Sandbox Code Playgroud)
我试图用gslHaskell 包装更多内容,并尝试理解示例代码的每一行。那为什么用Data.Coerce在这里呢?
haskell ×6