简体   繁体   中英

haskell: understanding types and functions

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:

  1. even x = x 'mod' 1 == 1

  2. chart xy = [y| x <- [1..x]]

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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