我对Haskell中的数据类型有一点问题,我想我应该先发布一些代码来帮助理解这个问题
helper :: (MonadMask a, MonadIO a, Functor a) => Expr -> String -> a (Either InterpreterError Int)
helper x y = ( getEval ( mkCodeString x y ) )
-- Creates Code String
mkCodeString :: (Show a) => a -> String -> String
mkCodeString x y = unpack (replace (pack "Const ") (pack "") (replace (pack "\"") (pack "") (replace (pack "Add") (pack y) (pack (show x) ) ) ) )
-- Calculates String
getEval :: (MonadMask m, MonadIO m, Functor m) => [Char] -> m (Either InterpreterError Int)
getEval str = (runInterpreter (setImports ["Prelude"] >> interpret str (as ::Int)))
-- | A test expression.
testexpression1 :: Expr
testexpression1 = 3 + (4 + 5)
-- | A test expression.
testexpression2 :: Expr
testexpression2 = (3 + 4) + 5
-- | A test expression.
testexpression3 :: Expr
testexpression3 = 2 + 5 + 5我像这样使用辅助函数"helper "(+)“,它返回值"Right 12”,类型为“but testexpression3”,但我只想要“Int”值"12“
我尝试了函数-> "getValue (Right x) = x“,但是我没有得到Int值。经过一段时间的测试后,我认为这是我所使用的Monads的问题。
如果我像这样测试助手函数的类型:":t (helper testexpression1 "(+)")“我会得到它:"(... ::(Functor a,MonadIO a,MonadMask a) => a( InterpreterError Int)”
我如何才能让这样的东西工作:编写"getValue (helper testexpression1 "(+)")“并获得"12”::Int
我知道代码没有任何意义,但这是一个家庭作业,我想用haskell.Hope尝试一些东西你有比我更多的想法
很抱歉我的英语不好,我已经开始学英语了,但我才刚刚开始,谢谢你的每一个想法和每件事。
编辑,以下是代码中缺少的内容:
import Test.HUnit (runTestTT,Test(TestLabel,TestList),(~?))
import Data.Function (on)
import Language.Haskell.Interpreter -- Hint package
import Data.Text
import Data.Text.Encoding
import Data.ByteString (ByteString)
import Control.Monad.Catch
-- | A very simple data type for expressions.
data Expr = Const Int | Add Expr Expr deriving Show
-- | 'Expression' is an instance of 'Num'. You will get warnings because
-- many required methods are not implemented.
instance Num Expr where
fromInteger = Const . fromInteger
(+) = Add
-- | Equality of 'Expr's modulo associativity.
instance Eq Expr where
(==) x1 x2 = True --(helper x1 "(+)") == (helper x2 "(+)") && (helper x1 "(*)") == (helper x2 "(*)") 该函数也在文件中...我文件中的其他内容都是我为自己创建的一些测试用例。
发布于 2014-07-05 01:47:07
helper textExpr "(+)"不是Either InterpreterError Int类型,而是(MonadMask a, MonadIO a, Functor a) => a (Either InterpreterError Int)类型。对于我们的目的,可以将后面的tyoe视为IO (Either InterpreterError Int)。
一般来说,IO a类型的东西(例如IO (Either InterpreterError Int))在最严格的意义上不包含a类型的值,因此您不能随意提取一个值。IO a类型的东西是一个操作,当执行该操作时,将产生a类型的值。Haskell只执行一个名为main的操作。也就是说,它允许我们从较小的操作中轻松地构建更大的操作。
main = helper textExpr "(+)" >>= print那里的运算符(>>=)是一个一元绑定。有关monads的更多信息,请参见You Could Have Invented Monads!。有关如何构建IO Monad的想法,请参阅Free Monads for Less (Part 3 of 3): Yielding IO (在“谁需要RealWorld?”一节)或者Idris' implementation of IO --但请记住,IO Monad在Haskell中是不透明和抽象的;除非您正在编写IO a (应用程序),否则不要期望能够从Haskell值中获得a值。
https://stackoverflow.com/questions/24562432
复制相似问题