简体   繁体   English

关于自定义数据类型和Haskell的困惑

[英]Confusion about custom data types and Haskell

data Quant = Single | Multiple deriving (Show, Read, Eq)

data ListUnit = ListUnit {
    quant :: Quant,
    num :: Int,
    letter :: Char
    } deriving (Show, Read, Eq)

data ListUnit2 = ListUnit2 Quant Int Char deriving (Show, Read, Eq)

decodeModified :: Quant -> Int -> Char -> Char
decodeModified _ _ ls = ls

decodeModified2 :: ListUnit2 -> Char
decodeModified2 _ _ ls = ls

I'm new to data types in Haskell. 我是Haskell中数据类型的新手。 I'm wondering why ListUnit works but I'm having problems with ListUnit2. 我想知道为什么ListUnit可以工作,但ListUnit2却有问题。 I know I shouldn't have to break out all of ListUnits values like I do in the first instance. 我知道我不必像在第一个实例中那样打破所有ListUnits值。 But when I don't, GHC that I'm not passing enough arguments. 但是,如果我不这样做,GHC表示我没有传递足够的论点。 I don't see how what I'm doing is different than LYAH in the Shapes example . Shapes示例中,我看不到我在做什么与LYAH有什么不同。

In case anyone is wondering, this is for "99 Problems" #11. 如果有人想知道,这是针对“ 99问题”#11的。 The data I want to model is [Multiple 4 'a',Single 'b',Multiple 2 'c', Multiple 2 'a',Single 'd',Multiple 4 'e'] . 我要建模的数据是[Multiple 4 'a',Single 'b',Multiple 2 'c', Multiple 2 'a',Single 'd',Multiple 4 'e']

The problem is that this: 问题是:

decodeModified2 :: ListUnit2 -> Char

means " decodeModified2 takes a ListUnit2 (type) and returns a Char ", whereas this: 意思是“ decodeModified2采用一个ListUnit2 (类型)并返回一个Char ”,而这是:

decodeModified2 _ _ ls = ls

means " decodeModified2 takes three arguments, discarding the first two and returning the third". 意思是“ decodeModified2接受三个参数,丢弃前两个参数并返回第三个参数”。 These two statements are incompatible. 这两个语句不兼容。

I think what you meant to write is: 我认为您的意思是:

decodeModified2 (ListUnit2 _ _ ls) = ls

which means " decodeModified2 takes a value constructed by ListUnit2 (function) with three arguments, discarding the first two and returning the third". 这意味着“ decodeModified2采用由ListUnit2 (函数)构造的具有三个参数的值,丢弃前两个参数并返回第三个参数”。

Does that make sense? 那有意义吗?


Edited to add after your comment below: And similarly, when you call decodeModified2 , you need to pass an instance of ListUnit2 (type) . 编辑后在下面的注释后添加 :同样,当您调用 decodeModified2 ,您需要传递ListUnit2 (类型)的实例。 For example, you can write something like decodeModified2 (ListUnit2 3 's' 'x') , using the value constructor ListUnit2 (function) to create an instance of ListUnit2 (type) . 例如,您可以使用值构造函数ListUnit2 (函数)创建ListUnit2 (类型)的实例,编写类似decodeModified2 (ListUnit2 3 's' 'x') 类的内容 (Or, more interestingly: you can create an instance of ListUnit2 (type) in one place and then call decodeModified2 in a different place, passing said instance.) (或者,更有趣的是:您可以在一个地方创建ListUnit2 (类型)的实例,然后在另一个地方调用decodeModified2 ,并传递该实例。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM