Back to Browse

Haskell 2c: Lists

18.5K views
Jan 27, 2015
8:12

Haskell 2c: Introduction to Lists Much like shopping lists in the real world, lists in Haskell are very useful. It's the most used data structure and it can be used in a multitude of different ways to model and solve a whole bunch of problems. Lists are SO awesome. In this section we'll look at the basics of lists, strings (which are lists) and list comprehensions. In Haskell, lists are a homogenous data structure. It stores several elements of the same type. That means that we can have a list of integers or a list of characters but we can't have a list that has a few integers and then a few characters. And now, a list! Note: We can use the let keyword to define a name right in GHCI. Doing let a = 1 inside GHCI is the equivalent of writing a = 1 in a script and then loading it. ghci: let lostNumbers = [4,8,15,16,23,42] ghci: lostNumbers [4,8,15,16,23,42] As you can see, lists are denoted by square brackets and the values in the lists are separated by commas. If we tried a list like [1,2,'a',3,'b','c',4], Haskell would complain that characters (which are, by the way, denoted as a character between single quotes) are not numbers. Speaking of characters, strings are just lists of characters. "hello" is just syntactic sugar for ['h','e','l','l','o']. Because strings are lists, we can use list functions on them, which is really handy. A common task is putting two lists together. This is done by using the ++ operator. ghci: [1,2,3,4] ++ [9,10,11,12] [1,2,3,4,9,10,11,12] ghci: "hello" ++ " " ++ "world" "hello world" ghci: ['w','o'] ++ ['o','t'] "woot" [1,2,3] is actually just syntactic sugar for 1:2:3:[]. [] is an empty list. If we prepend 3 to it, it becomes [3]. If we prepend 2 to that, it becomes [2,3], and so on. Note: [], [[]] and[[],[],[]] are all different things. The first one is an empty list, the seconds one is a list that contains one empty list, the third one is a list that contains three empty lists.

Download

0 formats

No download links available.

Haskell 2c: Lists | NatokHD