1

I've learned in Scheme and Lisp how to do a let that encases a map that takes an anonymous (lambda) function and list and gives back a "worked on by the function" list or answer. Can someone show me a bare-bones version of this in SML?

Update:

Here's a very simple map and anonymous function combo in Scheme:

(map (lambda (x) (+ x 1)) ’(4 5 8))

which produces the list

 ’(5 6 9)

Again, this is very common.

Here's a Lisp function using all three:

(defun sequence1_v1 (vallist)
     (let ((a 4))
       (mapcar #'(lambda (val)
                   (/ (+ (* -3 val a) 10) (+ (* (expt val 2) (expt a 2)) 1)))
               vallist)
       ))

The math is just a sequence generator and the value of a set to 4 means the 4th element of the sequence. If we ask for which of the following values of k will a_4 be positive, −2, −1, 0, 1, or 2, we have

(sequence1_v1 '(-2 -1 0 1 2)) ->

(34/65 22/17 10 -2/17 -14/65)

So the first three are positive. . . . So yes, the Lisp/Scheme world does this sort of thing a lot. Just wondering how this would look in ML.

147pm
  • 1,669
  • 13
  • 24
  • 1
    Your description isn't very clear. Could you post an example in Scheme or Lisp? – molbdnilo Dec 14 '18 at 11:20
  • There is really no need to use `let` if all you want to do is map an anonymous function over a list. I agree that your question is unclear. – John Coleman Dec 14 '18 at 17:55

1 Answers1

1

If your general form you want to translate is (in Scheme)

(define (name ls)
     (let (<bindings>)
       (map <function> ls)))

then it looks almost exactly the same in SML, but with different punctuation:

fun name ls = let <bindings> 
              in 
                  map <function> ls 
              end

And the anonymous function (lambda (parameters) body) is fn parameters => body.

(map (lambda (x) (+ x 1)) ’(4 5 8))

in SML:

map (fn x => x + 1) [4,5,8]

Your Lisp example, translated:

fun sequence1_v1 ls = 
    let val a = 4
    in
        map (fn v => (-3 * v * a + 10) / ((pow(v, 2) * (pow(a,2)) + 1)) ls
    end 
molbdnilo
  • 55,783
  • 3
  • 31
  • 71
  • This is what I was looking for. But since my question caused confusion, is this sort of `let`, `map` anonymous function combination atypical in ML? – 147pm Dec 15 '18 at 17:16
  • @147pm It's not atypical at all – it's as common as in Lisp or Scheme. I think its being so common that most people don't think of it as "a thing" was a major factor. – molbdnilo Dec 15 '18 at 17:26
  • Just one example, but probably the best book on ML "ML For the Working Programmer" makes no mention of anonymous functions. Maybe tangentially in the Lambda Calculus chapter, though. – 147pm Dec 15 '18 at 18:58
  • 1
    @147pm Yes it does; it even mentions them literally. See for instance chapter 5.1, "Anonymous functions with fn notation". The index lists "`fn` expressions" on pages 172-174, 178, 323, 427-428, and 462. – molbdnilo Dec 15 '18 at 20:10