Skip to content

Commit

Permalink
Document map function in array types (#221)
Browse files Browse the repository at this point in the history
* Document map function in array types

* Add description before section on fixed-sized arrays

Co-authored-by: Supun Setunga <supun.setunga@gmail.com>

* Update docs/cadence/language/values-and-types.mdx

---------

Co-authored-by: Supun Setunga <supun.setunga@gmail.com>
  • Loading branch information
darkdrag00nv2 and SupunS authored Aug 30, 2023
1 parent 9cb5d54 commit 32999ac
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions docs/cadence/language/values-and-types.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1252,6 +1252,69 @@ are available for both variable-sized and fixed-sized or variable-sized arrays.
// `fixedArrayReversedExample` is now `["PQR", "XYZ", "ABC"]`
```

-
```cadence
access(all)
fun map(_ f: (T: U)): [U]
```

Returns a new array whose elements are produced by applying the mapper function on each element
of the original array.
Available if `T` is not resource-kinded.

```cadence
let example = [1, 2, 3]
let trueForEven =
fun (_ x: Int): Bool {
return x % 2 == 0
}
let mappedExample: [Bool] = example.map(trueForEven)
// `mappedExample` is `[False, True, False]`
// `example` still remains as `[1, 2, 3]`
// Invalid: Map using a function which accepts a different type.
// This results in a type error, as the array contains `Int` values while function accepts
// `Int64`.
let functionAcceptingInt64 =
fun (_ x: Int64): Bool {
return x % 2 == 0
}
let invalidMapFunctionExample = example.map(functionAcceptingInt64)
```

`map` function is also available for fixed-sized arrays:

```cadence
access(all)
fun map(_ f: (T: U)): [U; N]
```

Returns a new fixed-sized array whose elements are produced by applying the mapper function on
each element of the original array.
Available if `T` is not resource-kinded.

```cadence
let fixedSizedExample: [String; 3] = ["ABC", "XYZYX", "PQR"]
let lengthOfString =
fun (_ x: String): Int {
return x.length
}
let fixedArrayMappedExample = fixedSizedExample.map(lengthOfString)
// `fixedArrayMappedExample` is now `[3, 5, 3]`
// `fixedSizedExample` still remains as ["ABC", "XYZYX", "PQR"]
// Invalid: Map using a function which accepts a different type.
// This results in a type error, as the array contains `String` values while function accepts
// `Bool`.
let functionAcceptingBool =
fun (_ x: Bool): Int {
return 0
}
let invalidMapFunctionExample = fixedSizedExample.map(functionAcceptingBool)
```

#### Variable-size Array Functions

The following functions can only be used on variable-sized arrays.
Expand Down

1 comment on commit 32999ac

@vercel
Copy link

@vercel vercel bot commented on 32999ac Aug 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.