#understanding use <- list.map

1 messages · Page 1 of 1 (latest)

quartz kestrel
#

was browsing some code and I seen this

const example_one = [
  "
some text
", "142"
]

use example <- list.map(example_one)
// part_one(s: String)
part_one(example)

I'm unsure as to why a function with the signature fn(List(String), fn(String) -> Nil) -> List(Nil) gives the type of example as String

#

correction should be tht I saw something similar in the repo and I wrote this myself

chrome crag
#

the code basically compiles to

const example_one = [
  "
some text
", "142"
]

list.map(example_one, fn (example) {
  part_one(example)
})

so example is the first argument in the function passed into map, so that's why it's a string

uneven kernel
#

just think of use that it takes the args on the left side and puts them into a callback on the right side

#

and... from that callback vanilla code use just removes indentation

#

and creates invisible blocks that do not end till the end of the function

#

you can escape that by wrapping use calls into gleam blocks

quartz kestrel
#

ahh that is clever, I ran a io.debug inside the function and it does indeed execute both elements in the list

uneven kernel
#

dont use use at first

#

and only use it if there is a lot of indentation

#

imho

quartz kestrel
uneven kernel
#

use + bool.guard may make sense as an early return replacement

#

opaque types, use and type params later

#

a bit more advanced stuff

quartz kestrel
#

thanks vm, didn't know there was an exercism track for this. will go through them all

uneven kernel
#

its awewsome sauce

sudden spindle
#

Ime use is at its best when APIs are designed to be used with it.
use with bool.guard is good for early returns
use with result.try is good for propagating errors to the caller like rusts ?
use is really good for middleware like in wisp
Etc.

I think generally you don’t want to use use with map, or any function where you want to come back out of the nesting before the top level function you’re writing code in ends. In these cases extracting a top level function is generally cleaner

quartz kestrel
#

yh thats fair, tbf I've little FP experience so was already not clear as just starting out, but probs over time I will start to understand where it is actually useful (like with result as you described)

sudden spindle
#

For example, you don’t need a lambda here, you can simply do list.map(example_one, part_one)

quartz kestrel
#

if you domt mind me sharing this was the rest of the code

  use example <- list.map(example_one)
  solve.part_one(example)
  |> should.equal(44)

but i guess both your advice would still hold true to (at least starting off) avoid use

sudden spindle
#

Ah yeah that makes sense, assuming they still need the list after the check. Otherwise could use list.each or list.all 🙂

uneven kernel
sudden spindle