[英]Mapping show to a list of a custom data type
As part of a large project at university to write an interpreter in Haskell for a simple custom language, I am trying to print some things to help me in my quest to write this thing. 作为一个大学的大型项目的一部分,该项目使用Haskell为一种简单的自定义语言编写了一个口译员,我正在尝试打印一些内容以帮助我寻求编写该内容的方法。
There's a custom data type 有一个自定义数据类型
data Prog = Prog [Func]
deriving (Show, Read)
and when I try to print an instance of this prog in the last line of this function 当我尝试在此函数的最后一行中打印此编的实例时
interpret :: Prog -> Vars -> String -> MaybeDebug -> IO ()
interpret prog vars entry _ = do
putStrLn "The interpreter isn't written yet. Better get onto that!"
putStrLn "\n\n"
putStrLn (show prog)
putStrLn "\n\n"
putStrLn (show vars)
putStrLn "\n\n"
putStrLn (show entry)
putStrLn "\n\n"
putStrLn (map show [func | func <- prog, (func_name func) == entry])
I receive an error "Couldn't match expected type 'Char' with actual type 'String'. 我收到错误消息“无法将预期的类型” Char”与实际类型” String”匹配。
I have been trying for some time to work out what the problem is here. 我已经尝试了一段时间以找出问题所在。 Why is it mentioning chars when this list comprehension returns a list of funcs?
当此列表理解返回函数列表时,为什么要提到字符?
map show [func | func <- prog, (func_name func) == entry]
produces a list of String
s, but putStrLn
takes a single String
, or [Char]
, as argument. 产生
String
的列表,但是putStrLn
采用单个String
或[Char]
作为参数。
So the expected type of the list elements is Char
, but the actual type is String
. 因此,列表元素的预期类型为
Char
,但实际类型为String
。
Depending on what output you desire, the last line should be something like 根据您想要的输出,最后一行应类似于
putStrLn (unlines $ map show [func | func <- prog, (func_name func) == entry])
or 要么
mapM_ putStrLn (map show [func | func <- prog, (func_name func) == entry])
(that would be better (那会更好
mapM_ print [func | func <- prog, (func_name func) == entry]
however). 然而)。
Then, in the list comprehension, when you write func <- prog
, prog
must be a list, but the argument to interpret
is a Prog
, a list wrapped in a constructor Prog
. 然后,在列表理解中,当您编写
func <- prog
, prog
必须是一个列表,但是要interpret
的参数是Prog
,它是包装在构造函数Prog
的列表。 You need to unwrap the list to use it in the list comprehension, for example 您需要解开列表才能在列表理解中使用它,例如
interpret prog@(Prog functions) vars entry _ = do
with an as-pattern, and then 用一个模式,然后
func <- functions
in the list comprehension. 在列表理解中。
As stated by Daniel, the problem is that putStrLn expects a String, not a list of Strings. 如Daniel所述,问题在于putStrLn需要一个String而不是String列表。
I suggest intercalate to print a comma separated list. 我建议插入以逗号分隔的列表。
putStrLn (intercalate ", " (map show [func | func <- prog, (func_name func) == entry]))
You need to import Data.List to get the intercalate function. 您需要导入Data.List以获得插入函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.