在Haskell中实现此monad/type? [英] Implementing this monad/type in Haskell?
问题描述
我真的无法弄清楚这样做的必要语法,这可能是由于我对类型的工作原理缺乏了解.
I really cannot figure out the syntax necessary for this, and it probably comes from my lack of understanding of how types work.
我想要一个类型DataPoint
,它存储一个元组(x, dataval)
或两个字段x和dataval(其中x是Double
而dataval是Complex Double
.
I want a type DataPoint
, which stores either a tuple (x, dataval)
or two fields x and dataval (where x is a Double
and dataval is a Complex Double
.
我想要一个Monad
实例,它的位置类似于:
I want a Monad
instance where it goes something like:
instance Monad (DataPoint x dataval) where
return dataval = DataPoint 0.0 dataval
DataPoint x dataval >>= f = DataPoint x (f dataval)
基本上,monad的值"是dataval,而x只是容器的一部分.
Basically, the "value" of the monad is dataval, and x is just a part of the container.
我认为我的语法不正确.如果我将DataPoint定义为
I don't think my syntax is correct though. If i define DataPoint as
data DataPoint x dataval = DataPoint { x :: Double
, dataval :: Complex Double }
那它应该工作,对吧?
只有我遇到不匹配的情况"
Only I get a "kind mismatch"
The first argument of `Monad' should have kind `* -> *',
but `DataPoint x dataval' has kind `*'
有人可以帮助我获得我要实现的功能/单子吗?
Can anyone help me get the functionality/monad I am trying to acheive?
推荐答案
就语法而言,
instance Monad (DataPoint x) where
-- etc
尽管我同意hammar的担忧,并认为您应该尝试使其成为Functor:
Although I share hammar's concerns and think you should be trying to make it a Functor instead:
instance Functor (DataPoint x) where
-- etc
您得到的同类错误
The first argument of `Monad' should have kind `* -> *',
but `DataPoint x dataval' has kind `*'
是因为Monad
和Functor
是适用于高阶类型的类型类(与Monoid
(适用于简单类型的类型类比较)相比).
is because Monad
and Functor
are typeclasses that apply to higher order types (compare with Monoid
, a typeclass that applies to simple types).
例如IO Int
不是 一元; IO ()
不是 一元; IO
是一个单子.
e.g. IO Int
is not a monad; IO ()
is not a monad; IO
is a monad.
我想要一个类型
DataPoint
,它存储一个元组(x, dataval)
或两个字段x
和dataval
(其中x
是Double
,而dataval
是Complex Double
. /p>
I want a type
DataPoint
, which stores either a tuple(x, dataval)
or two fieldsx
anddataval
(wherex
is aDouble
anddataval
is aComplex Double
.
data DataPoint a = DataPoint {x :: Double,
dataval :: a}
instance Functor DataPoint where
fmap f dataPoint = DataPoint {x = x dataPoint,
dataval = f (dataval dataPoint)}
这篇关于在Haskell中实现此monad/type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!