相关疑难解决方法(0)

如何在Haskell中为存在类型编写getter

感谢这个问题的答案,我已经定义了这样一个类型:

data Chain = forall a. Integral a => Chain [[a]] [a] a a
Run Code Online (Sandbox Code Playgroud)

我需要为每个字段或参数编写一个getter函数,如果你愿意的话.这是我的第一次尝试:

getSimplices (Chain simplices _ _ _) = simplices
Run Code Online (Sandbox Code Playgroud)

但是当我尝试编译ghc时会出现以下错误:

Chain.hs:10:40: error:
• Couldn't match expected type ‘t’ with actual type ‘[[a]]’
    because type variable ‘a’ would escape its scope
  This (rigid, skolem) type variable is bound by
    a pattern with constructor:
      Chain :: forall a. Integral a => [[a]] -> [a] -> a -> a -> Chain,
    in an equation for ‘getSimplices’
    at …
Run Code Online (Sandbox Code Playgroud)

haskell

2
推荐指数
2
解决办法
116
查看次数

GADT的功能

这是函数到多态数据类型的后续问题

数据类型Question使用Message(问题文本)和String -> a将用户输入映射到问题结果的函数()模拟问题/答案:

data Question where
  Simple :: (Typeable a, Show a) => Message -> (String -> a) -> Question
Run Code Online (Sandbox Code Playgroud)

此CLI程序应首先获取其名称,Question使用getQuestion函数查找实例,然后运行Question并打印出结果.

{-# LANGUAGE GADTs #-}

import Data.Typeable

type Message = String

data Question where
  Simple :: (Typeable a, Show a) => Message -> (String -> a) -> Question
  -- more constructors

yourName :: Question
yourName = Simple "Your name?" id

yourWeight :: Question
yourWeight = …
Run Code Online (Sandbox Code Playgroud)

haskell gadt

1
推荐指数
1
解决办法
179
查看次数

标签 统计

haskell ×2

gadt ×1