Haskell笔记 (3)—— list和tuple

(1)

Because strings are lists, we can use list functions on them.

举例如下:

> "Hello " ++ "world"
"Hello world"

(2)
:用来连接一个元素和list++连接两个list

>let list = [1, 2, 3, 4]
> print list
[1,2,3,4]
> [5] : list

<interactive>:23:1:
    Non type-variable argument in the constraint: Num [t]
    (Use FlexibleContexts to permit this)
    When checking that ‘it’ has the inferred type
      it :: forall t. (Num t, Num [t]) => [[t]]
> 5 : list
[5,1,2,3,4]

(3)

Ranges are a way of making lists that are arithmetic sequences of elements that can be enumerated. Numbers can be enumerated. One, two, three, four, etc. Characters can also be enumerated. The alphabet is an enumeration of characters from A to Z. Names can’t be enumerated. What comes after “John”?

举例如下:

> [1 .. 20]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

也可以指定元素之间的“步长”(24之间差2):

> [2, 4 .. 20]
[2,4,6,8,10,12,14,16,18,20]

另外,cycle循环一个list

cycle takes a list and cycles it into an infinite list. If you just try to display the result, it will go on forever so you have to slice it off somewhere.

> take 10 (cycle [1,2,3])  
[1,2,3,1,2,3,1,2,3,1]  
> take 12 (cycle "LOL ")  
"LOL LOL LOL "   

repeat循环一个元素

repeat takes an element and produces an infinite list of just that element. It’s like cycling a list with only one element.

> take 10 (repeat 5)  
[5,5,5,5,5,5,5,5,5,5]  

也可以使用replicate函数:

replicate function if you want some number of the same element in a list.

> replicate 10 5
[5,5,5,5,5,5,5,5,5,5]

(4)

list最后一个元素后面不能再跟,

>  [1,2]
[1,2]
> [1,2,]

<interactive>:12:6: parse error on input ‘]’

(5)

There’s a special type, () , that acts as a tuple of zero elements. This type has only one value, which is also written () . Both the type and the value are usually pronounced “unit.” If you are familiar with C, () is somewhat similar to void.

(6)fstsnd这两个函数只能操作包含两个元素的tuple

> :type fst
fst :: (a, b) -> a
> :type snd
snd :: (a, b) -> b

(7)

The list [1,2,3] in Haskell is actually shorthand for the list 1:(2:(3:[])), where [] is the empty list and : is the infix operator that adds its first argument to the front of its second argument (a list). (: and [] are like Lisp’s cons and nil, respectively.) Since : is right associative, we can also write this list as 1:2:3:[].

发表评论

邮箱地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.