List notation
From HaskellWiki
(Difference between revisions)
(there are cool things possible with bare list syntax) |
(see also as section) |
||
| (2 intermediate revisions not shown.) | |||
| Line 24: | Line 24: | ||
[] | [] | ||
</haskell> | </haskell> | ||
| - | * You can construct a singleton list with a [[operator | + | * You can insert elements or sub-lists conditionally. |
| + | <haskell> | ||
| + | infixr 5 ?:, ?++ | ||
| + | |||
| + | (?:) :: (Bool, a) -> [a] -> [a] | ||
| + | (?:) (b, x) = if b then (x:) else id | ||
| + | |||
| + | (?++) :: (Bool, [a]) -> [a] -> [a] | ||
| + | (?++) (b, x) = if b then (x++) else id | ||
| + | |||
| + | list = | ||
| + | [2,3] ++ | ||
| + | (x==5, 5) ?: | ||
| + | (x==7, listA) ?++ | ||
| + | [] | ||
| + | </haskell> | ||
| + | * You can construct a singleton list with a [[Section of an infix operator|section]] of the colon operator: <haskell>(:[]) :: a -> [a]</haskell>. | ||
* You can prepend an element to a list: <haskell>(x:) :: [a] -> [a]</haskell>. E.g. <haskell>iterate (' ':) []</haskell> creates a list of blank strings with increasing size very efficiently. | * You can prepend an element to a list: <haskell>(x:) :: [a] -> [a]</haskell>. E.g. <haskell>iterate (' ':) []</haskell> creates a list of blank strings with increasing size very efficiently. | ||
| - | See also | + | == See also == |
| + | |||
* [http://www.haskell.org/pipermail/haskell-cafe/2006-July/016655.html Haskell-Cafe thread: Comma in the front] | * [http://www.haskell.org/pipermail/haskell-cafe/2006-July/016655.html Haskell-Cafe thread: Comma in the front] | ||
[[Category:Idioms]] | [[Category:Idioms]] | ||
[[Category:Syntax]] | [[Category:Syntax]] | ||
Current revision
We are used to the list notation[0,1,2,3]
(0:1:2:3:[])
By using the syntactic sugar, we often miss the benefits of the direct notation.
- A trailing colon is like a terminator.
0 : 1 : 2 : 3 : []
- Thus it is more theoretically sound and easier to edit.
- You can easily mix elements and lists into a list by appending the corresponding operator in each line:
[1,2,3] ++ 4 : listA ++ 5 : listB ++ []
- You can insert elements or sub-lists conditionally.
infixr 5 ?:, ?++ (?:) :: (Bool, a) -> [a] -> [a] (?:) (b, x) = if b then (x:) else id (?++) :: (Bool, [a]) -> [a] -> [a] (?++) (b, x) = if b then (x++) else id list = [2,3] ++ (x==5, 5) ?: (x==7, listA) ?++ []
- You can construct a singleton list with a section of the colon operator: .
(:[]) :: a -> [a]
- You can prepend an element to a list: . E.g.
(x:) :: [a] -> [a]
creates a list of blank strings with increasing size very efficiently.iterate (' ':) []
