gusl: (Default)
[personal profile] gusl
One programming annoyance when writing loops is wanting to access each element of the list without passing the index, i.e. with code like: for (el in list) while simultaneously wanting to know the index without writing i=0 and i++.

I'm not aware of any solutions to this in current usage.

(no subject)

Date: 2010-04-28 03:10 am (UTC)
From: [identity profile] wjl.livejournal.com
In a sufficiently expressive language (e.g. SML), it is not difficult to get the behavior you want with a higher-order function. For example:
  local
    fun mapi_aux i f [] = []
      | mapi_aux i f (x::xs) = f (i, x) :: mapi_aux (i+1) f xs
  in
    (* mapi : (int * 'a -> 'b) -> 'a list -> 'b list *)
    fun mapi f list = mapi_aux 0 f list
  end

Now instead of for (el in list) { ... code(i, el) ... } you just say mapi (fn (i, el) => ... code(i, el) ...) list.

The Standard ML Basis has things like Array.iteri and Vector.mapi predefined:
  - Array.appi;
  val it = fn : (int * 'a -> unit) -> 'a array -> unit
  - Vector.mapi;
  val it = fn : (int * 'a -> 'b) -> 'a vector -> 'b vector

(no subject)

Date: 2010-04-28 03:16 am (UTC)
From: [personal profile] chrisamaphone
you beat me to it! i had the source for mapi in my copy buffer :)

February 2020

S M T W T F S
      1
2345678
9101112131415
16171819202122
23242526272829

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags