zzz6519003 / blog

My blog about coding
4 stars 1 forks source link

Haskell Day 1 (1) #83

Open zzz6519003 opened 7 years ago

zzz6519003 commented 7 years ago

Try an if/then statement:

 Prelude> if (5 == 5) then "true" 
<interactive>:1:23: parse error (possibly incorrect indentation)

That’s the first major departure from other languages in the book. In Haskell, indentation is significant. Haskell is guessing that there’s a follow-up line that is not indented correctly.

In Haskell, if is a function, not a control structure, meaning it returns a value just like any other function.

A Haskell function traditionally has two parts: the type declaration and the function declaration.

Remember, lists are homogeneous. You can’t add a list to a list of inte- gers, for example:

Prelude> [1]:[2, 3] 
<interactive>:1:8:
    No instance for (Num [t])
      arising from the literal `3' at <interactive>:1:8

You could, however, add a list to a list of lists or even an empty list:

Prelude> [1]:[[2], [3, 4]]
[[1],[2],[3,4]]

Prelude> [1]:[]

[[1]] 
module Main where
allEven :: [Integer] -> [Integer]
allEven [] = []
allEven (h:t) = if even h then h:allEven t else allEven t 

Our function takes a list of integers and returns a list of even integers. allEven for an empty list is an empty list. If there is a list, if the head is even, we add the head to allEven applied to the tail. If the head is odd, we discard it by applying allEven to the tail. No problem. Let’s look at some other ways to build lists.