Function as parameter to another function

Post Reply
Henko
Posts: 814
Joined: Tue Apr 09, 2013 12:23 pm
My devices: iPhone,iPad
Windows
Location: Groningen, Netherlands
Flag: Netherlands

Function as parameter to another function

Post by Henko »

It is not mentioned explicitly in the sB help info, but a function name may be passed to another function in the parameter list.

Code: Select all


x=3 ! prt(f(x))
end

def prt(x) ! print x ! end def

def f(x)
  return 4*x-3
end def

matt7
Posts: 115
Joined: Sun Jul 12, 2015 5:00 pm
My devices: iPhone
Location: USA

Re: Function as parameter to another function

Post by matt7 »

I don't think that's what is happening in your example. f(x) is being evaluated first, and then its return value is passed to function prt.

matt7
Posts: 115
Joined: Sun Jul 12, 2015 5:00 pm
My devices: iPhone
Location: USA

Re: Function as parameter to another function

Post by matt7 »

I have often times run into situations where function pointers would have been helpful, but I have refrained from requesting that feature because I thought it was a bit too far out of the realm of what Basic languages normally do.

My alternative has been to use numerical enumerations (but you could just use strings if you wanted to):

Code: Select all

' Enumeration for selected color mode:
(I usually put all enumerations for a program in one library file)
COLOR_MODE_RGB = 1
COLOR_MODE_HSL = 2

' . . .

' Then everywhere else in the program, I can refer to these with the variable names instead of memorizing that RGB is 1 and HSL is 2
SWITCH_TO_COLOR_MODE(COLOR_MODE_RGB)

' . . .

DEF SWITCH_TO_COLOR_MODE(cm)

  IF cm = COLOR_MODE_RGB THEN
    ' ...
  ELSE ' cm = COLOR_MODE_HSL
    ' ...
  END IF

END DEF

User avatar
Mr. Kibernetik
Site Admin
Posts: 4786
Joined: Mon Nov 19, 2012 10:16 pm
My devices: iPhone, iPad, MacBook
Location: Russia
Flag: Russia

Re: Function as parameter to another function

Post by Mr. Kibernetik »

Yes, functions as parameters is too much for BASIC language.
In my SPL language functions are the same objects as any other assignable object and can be passed as function parameters, saved into variables and so on. But this is very sophisticated for BASIC functionality.

Henko
Posts: 814
Joined: Tue Apr 09, 2013 12:23 pm
My devices: iPhone,iPad
Windows
Location: Groningen, Netherlands
Flag: Netherlands

Re: Function as parameter to another function

Post by Henko »

Henko wrote:
Fri Mar 01, 2019 3:36 pm
It is not mentioned explicitly in the sB help info, but a function name may be passed to another function in the parameter list.

Code: Select all


x=3 ! prt(f(x))
end

def prt(x) ! print x ! end def

def f(x)
  return 4*x-3
end def
Yes, Matt is right of course. The "def prt(x)" clearly indicates that a value is expected.

Post Reply