6

Creating a List of Ints and Functions Int - & gt; Int - & gt; Int

 2 years ago
source link: https://www.codesd.com/item/creating-a-list-of-ints-and-functions-int-int-int.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Creating a List of Ints and Functions Int - & gt; Int - & gt; Int

advertisements

Apart from creating functions that do simple things to lists, I'm pretty new to haskell. I would like to create a list which contains things of type Int, and functions of type Int -> Int -> Int.

Here is what I have tried:

data Token = Value Int | Operator (Int -> Int -> Int)

tokens :: [Token]
tokens = [12, (+)]

but I get the following error

Couldn't match expected type `Token'
            with actual type `Integer -> Integer -> Integer'
In the expression: (+)
In the expression: [12, (+)]
In an equation for `tokens': tokens = [12, (+)]

I'm not sure why this doesn't work, can anyone point me in the right direction?


You need to use your constructors to obtain values of type Token. For example, 12 is not of type Token, it is of type Int (well, Num a => a). Similarly, (+) is not a token but a function Int -> Int -> Int. Notice that Token /= Int -> Int -> Int.

Fortunately you have defined a few constructors such as Value :: Int -> Token and Operator :: (Int -> Int -> Int) -> Token. So using those we get:

tokens :: [Token]
tokens = [Value 12, Operator (+)]

Tags haskell

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK