[erlang-questions] Proposal: add lists:intersperse/2 and lists:intercalate/2

Siraaj Khandkar siraaj@REDACTED
Tue Mar 8 15:02:42 CET 2016


On 3/7/16 7:24 PM, Richard A. O'Keefe wrote:
> On 8/03/16 5:59 am, Siraaj Khandkar wrote:
>
>> Both of the above results are functions of 2 sequences, the difference
>> is that 1st works with a pre-computed list, while the 2nd works with a
>> an infinite stream of 0s.
>
> (A) No.  0 is not an infinite stream of 0s.

Then, given a 0 and [1, 2, 3], you can't do much better than
[1, 0, 2, 3]


> (B) Erlang doesn't have infinite lists.

There's no primitive named "sequence" in Erlang either.


> (C) Haskell *does* have infinite lists, but you still have to
>     write cycle [0] to get one.
> (D) I was discussing *specific* code definitions:
>
> intersperse(Sep, [X|Xs]) -> [X | intersperse_(Xs)];
> intersperse(_, []) -> [].
>
> intersperse_(Sep, [X|Xs]) -> [Sep,X | intersperse_(Xs)];
> intersperse_(_, []) -> [].

The above function clearly constructs the second sequence (of Seps) on 
the fly.

Please note the obvious similarity to:

-spec seq(A) :: nil | {cons, A, seq(A)}.

>
> interleave([X|Xs], [Y|Ys]) -> [X,Y | interleave(Xs, Ys)];
> interleave([], []) -> [].
>
> which have quite distinct interfaces.  interleave/2 takes two
> list(T) sequences; intersperse/2 takes a T and a list(T).
>
> Someone raised the issue of finding functions.
> It's actually quite hard in most programming languages to guess
> the names of most built-in functions from their meaning.
> For example, who would have guess that "read a line from
> standard input" was called gets() in C?
>
> Haskell has a web interface where you can give the *type* of
> a function and get a list of well-known functions with that
> type.  Squeak has (or had, I haven't updated in a while) an
> IDE interface where you can give an input-output *example*
> of a function and get a list of well-known functions that give
> that output for that input.  It might be a good idea to do
> that for at least the Erlang lists module, so that you could
> do function_finder:find(",", ["a","b"], "a,b")
> ==> lists:intercalate/2
> and function_finder:find([d,r,e,a,d], [a,d,d,e,r])
> ==> lists:sort/1

These are, indeed, great ideas!

There's been an effort to do similar for OCaml:
http://ocamloscope.herokuapp.com/

Which, I have to admit, I have not felt the urge to use in practice.



More information about the erlang-questions mailing list