listfunctionhaskellnlp-question-answeringvalue-constructor

Value constructors in haskell


I have a question about Haskell. I'm new so I don't understand too well, but if anyone could help me I'd really appreciate. I have this exercise from a book that I bought.

Create a type Question with value contructors Sim or Nao. Make a function that:

I tried this code:

module Question where 

data Question = Yes | No deriving Show

questNum :: Question -> Int
questNum No = 0
questNum Yes = 1

listQuest :: [Question] -> [Int]
listQuest listQuestion =  [ questNum quest | quest <- listQuestion ]

I'm lost in the prompt matter. Don't know what to write to use the function.

Thanks for the help


Solution

  • There are several ways to do that, you did it by list comprehension, another way is using map:

    listQuest :: [Question] -> [Int]
    listQuest xs = map questNum  xs
    

    shorter

    listQuest :: [Question] -> [Int]
    listQuest  = map questNum  
    

    using foldr (it is also a way to say map, indeed you can write the general map using foldr):

    listQuest :: [Question] -> [Int]
    listQuest = foldr (\x rs -> questNum x : rs) []
    

    and the old good pattern matching (is map, but with pattern matching):

    listQuest :: [Question] -> [Int]
    listQuest []  = []
    listQuest (x:xs) = questNum x : listQuest xs  
    

    your way, and all of this, are equivalent.

    On the prompt:

    Then on the prompt you type something like:

    $> :l file_name.hs
    $> listQuest [Yes, Yes, No]
    $> [1,1,0]