How to translate logical notation to Haskell syntax

后端 未结 4 967
天命终不由人
天命终不由人 2021-01-25 13:22

I\'ve recently picked up Haskell at uni and I\'m working my way through a set of exercises, here\'s a snippet of one that I can\'t make sense of:

\"Consider the followin

4条回答
  •  旧时难觅i
    2021-01-25 14:04

    How do I declare type or data(not a variable) for fixed values, namely 0-9?

    You can define a type, like

    data Digit = Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine deriving (Eq, Show)
    

    This represents the num in your problem. Obviously we cannot use 0, 1, 2, 3, ... since they are already interpreted as numbers in Haskell.

    Then, you can define

    data Number = Single Digit | Many Digit Number deriving (Eq, Show)
    

    which is equivalent to int in your problem. This type represents one (Single ...) or more (Many ...) digits, which together make a one decimal number. For example, with these data types a number 361 would be Many Three (Many Six (Single One)).

    Also, how can I put symbols like - or + in a declaration?

    There is no way to put those symbols in type or data declarations. You can use, however, names for the operations, like Sum, Sub and Mul. Then the expr of the grammar of your problem would translate to

    data Expr   = Lit Number
                | Sub Expr Expr
                | Sum Expr Expr
                | Mul Expr Expr
                deriving (Eq, Show)
    

    If we would have a string "+ (- (2 5) (1 3)) 3", which represents an expression in the prefix calculator language of your problem , it would be parsed to Sum (Sub (Lit (Many Two (Single Five))) (Lit (Many One (Single Three)))) (Single Three).

提交回复
热议问题