Reputation: 11
In an attempt to learn how haskell works, I created the following statements. I am trying to understand what their types are; can anybody let me know if I am the right track?
statement type
['h', 'e', 'l', 'l', 'o'] ['h', 'e', 'l', 'l', 'o'] :: [char]
[(9,8),(7,6),(5,4)] [(9,8),(7,6),(5,4)] :: [int a, int b] => [(a,b)]
if that's correct, can someone help me understand the type / function for these statements:
even x = x 'mod' 1 == 1
chart x y = [y| x <- [1..x]]
Upvotes: 1
Views: 132
Reputation: 3202
Types in Haskell are capitalized; yes, it matters.
['h', 'e', 'l', 'l', 'o'] :: [Char]
Correct, although [Char] and String are type synonyms, and String looks nicer. :P
[(9,8),(7,6),(5,4)] :: (Num a, Num b) => [(a,b)]
Multiple constraints are in round brackets. There's no "int" typeclass.
even x = x `mod` 1 == 1
even :: Integral a => a -> Bool
Make sure you use backticks and not single quotes; yes, it matters. In ghci use :t to check the type of mod and (==), and use :i to check the relationship between Num and Integral, and you should be able to put this together.
chart x y = [y | x <- [1..x]]
chart :: (Num a, Enum a) => a -> b -> [b]
For this, you have to know the "long name" of [a..b] is enumFromTo, as well as how to desugar list comprehensions. List comprehensions aren't hard, but there's already good descriptions in RWH, LYAH, and the Haskell 2010 Report, so I won't leave one here.
Upvotes: 2
Reputation: 198526
Your type signatures are not quite correct. Pay attention to capitalisation, it's [Char]
; and it's Num
and not int
; and also wrong brackets: (Num a, Num b) => [(a, b)]
. As for the rest...
$ ghci
[...]
Prelude> let even x = x `mod` 1 == 1
Prelude> :t even
even :: Integral a => a -> Bool
Prelude> let chart x y = [y| x <- [1..x]]
Prelude> :t chart
chart :: (Enum t1, Num t1) => t1 -> t -> [t]
Also, note the backticks on the mod
, not quotes.
EDIT following the comments:
It seems that you also want the clarification on the meaning of the functions even
and chart
.
Even of x is the value of whether the remainder when you divide x by one is one
Unfortunately, the function is incorrectly written, since all integers are divisible by 1
, and the remainder is never 1
. The correct definition for even
is
even x = x `mod` 2 == 0
Even of x is the value of whether the remainder when you divide x by two is zero
As for chart
,
Chart of a value x and a number y is a list consisting of values y for each element in a list of numbers from 1 to x
so if you do chart 3 5
, you will have a list of threes for each element in [1, 2, 3, 4, 5], so five threes: [3, 3, 3, 3, 3]
Upvotes: 5