【问题标题】:mapping multiple functions in haskell在haskell中映射多个函数
【发布时间】:2016-06-07 17:03:38
【问题描述】:

我正在研究一种在 Haskell 中表示内存的方法,看起来像这样......

data MemVal = Stored Value | Unbound
          deriving Show

type Memory = ([Ide],Ide -> MemVal)

作为标识符被称为将其添加到标识符列表中。如果程序中发生错误,我希望能够调用最新使用的标识符。到目前为止,我有这个......

display :: Memory -> String
display m = "Memory = " ++ show (map (snd m) (fst m)) ++ " "

但想知道是否有办法将标识符的名称映射到 (fst m) 以及函数 (snd m),因此输出将类似于...

Memory = [sum = stored Numeric 1, x = stored Boolean true]

谢谢。

【问题讨论】:

  • 你能创建一个minimal working example吗?例如,什么是 Ide?什么是价值?
  • show [(ident, snd m ident) | ident <- fst m]怎么样
  • 值为 data Value = Numeric Integer | Boolean Bool | ERROR deriving Show 并且 Ide 是存储值或由 MemVal 定义的未绑定

标签: haskell


【解决方案1】:

你可能想要这样的东西

display :: Memory -> String
display (ides, mem) = 
   "Memory = [" ++ unwords (map (\x -> x ++ "=" ++ mem x) ides) ++ "]"

【讨论】:

    【解决方案2】:

    我猜这就是你所追求的:

    import Data.List (intercalate)
    
    display (Memory ids f) = "Memory = [" ++ (intercalates ", " assigns) ++ "]"
      where assigns = [ show i ++ " = " ++ show (f i) | i <- ids ]
    

    这里assigns 是一个类似的列表:

    [ "sum = stored Numeric 1", "x = stored Boolean true", ...]
    

    intercalate ", " assigns 将字符串连接在一起。

    我使用解构来避免引用 fst ...snd ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多