Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #5168 > unrolled thread

Call by Result

Started byGene Wirchenko <genew@ocis.net>
First post2011-06-09 23:03 -0700
Last post2011-06-17 11:43 -0300
Articles 20 on this page of 81 — 21 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-09 23:03 -0700
    Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-10 07:33 +0000
      Re: Call by Result Nigel Wade <nmw-news@ion.le.ac.uk> - 2011-06-10 10:03 +0100
        Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-10 09:47 +0000
        Re: Call by Result Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2011-06-10 08:23 -0300
          Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-10 13:12 +0000
            Re: Call by Result Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2011-06-10 15:44 -0300
              Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-12 16:29 +0000
                Re: Call by Result Silvio <silvio@moc.com> - 2011-06-12 23:00 +0200
                  Re: Call by Result Silvio <silvio@moc.com> - 2011-06-12 23:06 +0200
                  Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-14 10:52 +0000
                    Re: Call by Result Silvio <silvio@moc.com> - 2011-06-14 17:13 +0200
                      Re: Call by Result Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2011-06-14 17:58 -0300
                        Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-14 21:18 +0000
                          Re: Call by Result Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2011-06-14 20:14 -0300
                            Re: Call by Result Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2011-06-15 07:13 -0300
                              Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-15 12:50 +0000
                                Re: Call by Result Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2011-06-15 18:52 -0300
                          Re: Call by Result lewbloch <lewbloch@gmail.com> - 2011-06-15 07:06 -0700
                    Re: Call by Result Michael Wojcik <mwojcik@newsguy.com> - 2011-06-15 21:33 -0400
                      Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-16 11:03 +0000
                        Re: Call by Result "H.J. Sander Bruggink" <sander.bruggink@uni-due.de> - 2011-06-16 13:09 +0200
                          Re: Call by Result Lewis Bloch <lewisbloch@google.com> - 2011-06-16 06:59 -0700
                            Re: Call by Result "John B. Matthews" <nospam@nospam.invalid> - 2011-06-16 23:14 -0400
          Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-10 11:31 -0700
            Re: Call by Result Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2011-06-12 14:27 -0300
        Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-10 07:20 -0700
        Re: Call by Result Patricia Shanahan <pats@acm.org> - 2011-06-10 09:30 -0700
          Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-10 11:44 -0700
      Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-10 11:26 -0700
        Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-11 15:07 +0000
          Re: Call by Result Abu Yahya <abu_yahya@invalid.com> - 2011-06-11 23:00 +0530
            Re: Call by Result Martin Gregorie <martin@address-in-sig.invalid> - 2011-06-11 19:36 +0000
              Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-11 21:06 +0000
                Re: Call by Result Martin Gregorie <martin@address-in-sig.invalid> - 2011-06-12 10:53 +0000
                  Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-12 09:28 -0700
                    Re: Call by Result Martin Gregorie <martin@address-in-sig.invalid> - 2011-06-12 17:48 +0000
                      Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-12 13:19 -0700
              Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-11 15:39 -0700
                Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-12 11:07 +0000
                  Re: Call by Result markspace <-@.> - 2011-06-12 07:02 -0700
                  Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-12 09:39 -0700
                    Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-14 10:29 +0000
                      Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-14 09:14 -0700
                        Re: Call by Result markspace <-@.> - 2011-06-14 09:21 -0700
                          Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-14 09:53 -0700
                        Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-14 09:57 -0700
              Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-12 21:44 -0700
          Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-12 21:40 -0700
    Re: Call by Result Patricia Shanahan <pats@acm.org> - 2011-06-10 01:30 -0700
      Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-10 11:45 -0700
    Re: Call by Result Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-06-10 07:50 -0400
    Re: Call by Result Silvio <silvio@moc.com> - 2011-06-10 15:35 +0200
    Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-10 13:56 +0000
    Re: Call by Result Peter Duniho <NpOeStPeAdM@NnOwSlPiAnMk.com> - 2011-06-10 07:22 -0700
      Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-10 11:56 -0700
      Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-10 11:57 -0700
        Re: Call by Result Patricia Shanahan <pats@acm.org> - 2011-06-10 13:50 -0700
          Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-12 21:53 -0700
            Re: Call by Result Arved Sandstrom <asandstrom3minus1@eastlink.ca> - 2011-06-13 07:20 -0300
              Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-13 08:08 -0700
        Re: Call by Result Wojtek <nowhere@a.com> - 2011-06-11 16:35 -0700
          Re: Call by Result Martin Gregorie <martin@address-in-sig.invalid> - 2011-06-12 11:05 +0000
          Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-12 21:56 -0700
            Re: Call by Result Wojtek <nowhere@a.com> - 2011-06-14 00:40 -0700
      Re: Call by Result Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-06-11 21:18 +0000
    Re: Call by Result markspace <-@.> - 2011-06-10 08:43 -0700
    Re: Call by Result RedGrittyBrick <RedGrittyBrick@spamweary.invalid> - 2011-06-10 17:01 +0100
      Re: Call by Result Martin Gregorie <martin@address-in-sig.invalid> - 2011-06-10 16:55 +0000
      Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-10 11:59 -0700
        Re: Call by Result Wojtek <nowhere@a.com> - 2011-06-11 16:24 -0700
          Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-12 21:59 -0700
            Re: Call by Result Paul Cager <paul.cager@googlemail.com> - 2011-06-13 07:53 -0700
            Re: Call by Result Wojtek <nowhere@a.com> - 2011-06-14 00:43 -0700
    Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-10 11:55 -0700
    Re: Call by Result Steven Simpson <ss@domain.invalid> - 2011-06-11 09:09 +0100
    Re: Call by Result Cholo Lennon <chololennon@hotmail.com> - 2011-06-16 11:30 -0300
      Re: Call by Result Paul Cager <paul.cager@googlemail.com> - 2011-06-17 02:38 -0700
        Re: Call by Result Gene Wirchenko <genew@ocis.net> - 2011-06-17 12:06 -0700
      Re: Call by Result lewbloch <lewbloch@gmail.com> - 2011-06-17 06:40 -0700
        Re: Call by Result Cholo Lennon <chololennon@hotmail.com> - 2011-06-17 11:43 -0300

Page 1 of 5  [1] 2 3 4 5  Next page →


#5168 — Call by Result

FromGene Wirchenko <genew@ocis.net>
Date2011-06-09 23:03 -0700
SubjectCall by Result
Message-ID<nkc3v61jg7i21l7n482ce561dq9fdogg3m@4ax.com>
Dear Java'ers:

     I wish to call by result with a method.  Is it possible?  If not,
can it be easily simulated in an unnasty way?

     I am writing a simple preprocessor.  I have a few spots where a
string needs to be parsed.  I want to call something like this:
          String ReturnString="";
          boolean DidItWork=GetString(ReturnString);
          if (!DidItWork)
             // too bad
It is not acceptable to have a special String value mean failure.  I
want the method to be able to return any potential string.

Sincerely,

Gene Wirchenko

[toc] | [next] | [standalone]


#5169

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2011-06-10 07:33 +0000
Message-ID<slrniv3i5o.phi.avl@gamma.logic.tuwien.ac.at>
In reply to#5168
Gene Wirchenko <genew@ocis.net> wrote:
>      I am writing a simple preprocessor.  I have a few spots where a
> string needs to be parsed.  I want to call something like this:
>           String ReturnString="";
>           boolean DidItWork=GetString(ReturnString);
>           if (!DidItWork)
>              // too bad
> It is not acceptable to have a special String value mean failure.  I
> want the method to be able to return any potential string.

There's three basic ways to do it:

1) Return null to indicate failure. (Unless you consider null to
   also be a valid String-value - That typically depends on the
   context and I didn't read your wording as being explicit on that.)
    String retVal = getString();
    if (retVal == null) { /* too bad */ }
    This won't work, though, if you need to return a String both
    on failure and success.

2) instead of the string, pass a mutable container of a string:
    String[] stringContainer = new String[1];
    boolean didItWork = getString(stringContainer);
    if (didItWork) { /* stringContainer[0] has the string */ }

  and within GetString:
    public boolean getString(String[] strCont) {
            strCont[0] = "blah"; return true;
    }

3) encode the String: e.g.: prepend a particular text to "success"-
    strings, and a different text to "failure"-strings:

    public String getString(String[] strCont) {
        if (ok()) { return "+" + okMessage; }
        else      { return "-" + errMessage; }
    }
  use:
    String retVal = getString();
    if (retVal == null || retVal.length() == 0) { /* internal error */ } else
    if ( retVal[0] == '+' ) { 
        // All's well that ends well:  retVal.subString(1)
    } else if ( retVal[0] == '-' ) {
        // Uh-Oh!:  retVal.subString(1)
    } else {  /* internal error */ }


PS: Surely, someone will soon point out coding-conventions about
  upper-/lower-casing different kinds of identifiers. I dare to agree
  in advance.  (Btw., I changed to conformant casing in my examples.) 

[toc] | [prev] | [next] | [standalone]


#5172

FromNigel Wade <nmw-news@ion.le.ac.uk>
Date2011-06-10 10:03 +0100
Message-ID<95e4uuF3cvU1@mid.individual.net>
In reply to#5169
On 10/06/11 08:33, Andreas Leitgeb wrote:
> Gene Wirchenko <genew@ocis.net> wrote:
>>      I am writing a simple preprocessor.  I have a few spots where a
>> string needs to be parsed.  I want to call something like this:
>>           String ReturnString="";
>>           boolean DidItWork=GetString(ReturnString);
>>           if (!DidItWork)
>>              // too bad
>> It is not acceptable to have a special String value mean failure.  I
>> want the method to be able to return any potential string.
> 
> There's three basic ways to do it:
> 
> 1) Return null to indicate failure. 
> 
> 2) instead of the string, pass a mutable container of a string:
> 
> 3) encode the String: e.g.: prepend a particular text to "success"-

Are 1) and 3) not precluded by the proviso "It is not acceptable to have
a special String value mean failure".

A fourth way would be to return a class/object containing both the
boolean and the String. To me, this would be the natural OO way of
returning more information than a primitive type.

And a 5th way could be to return the String and throw an Exception if it
did not work. Some purists may argue that failure to work is not
strictly an exception, but if it gets the job done...

-- 
Nigel Wade


[toc] | [prev] | [next] | [standalone]


#5173

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2011-06-10 09:47 +0000
Message-ID<slrniv3q1b.phi.avl@gamma.logic.tuwien.ac.at>
In reply to#5172
Nigel Wade <nmw-news@ion.le.ac.uk> wrote:
> On 10/06/11 08:33, Andreas Leitgeb wrote:
>> Gene Wirchenko <genew@ocis.net> wrote:
>>> It is not acceptable to have a special String value mean failure.  I
>>> want the method to be able to return any potential string.

>> There's three basic ways to do it:
>> 1) Return null to indicate failure. 
>> 2) instead of the string, pass a mutable container of a string:
>> 3) encode the String: e.g.: prepend a particular text to "success"-
> Are 1) and 3) not precluded by the proviso "It is not acceptable to have
> a special String value mean failure".

It is conceivable that "1)" might be, but (in my understanding) not implied.
It boils down to whether one considers null to be a String value. If you
think "of course", then so be it. I don't really care.

"3)" is rather not, because it is just a different way of implementing
your "4)" below. (Although it might take some more fuss to also encode 
possible nulls for success and failure into the return string, if at all
needed.) Both the boolean and the original string value can be safely
extracted from the encoded string. I'm speaking of "String values" here,
such as identified by .equals(), not of String instances, though. So, if
the latter has to be preserved, too, then "3)" would indeed be ruled out.

> A fourth way would be to return a class/object containing both the
> boolean and the String. To me, this would be the natural OO way of
> returning more information than a primitive type.
>
> And a 5th way could be to return the String and throw an Exception if it
> did not work. Some purists may argue that failure to work is not
> strictly an exception, but if it gets the job done...

"4)" and "5)" are both very good ideas, both nicer/cleaner than mine, and
I'm a bit embarrassed for not having thought of them, myself. (Well, at
least, mine are a bit shorter to implement ;-)
"5)" has also been suggested by Patricia.

[toc] | [prev] | [next] | [standalone]


#5175

FromArved Sandstrom <asandstrom3minus1@eastlink.ca>
Date2011-06-10 08:23 -0300
Message-ID<G8nIp.1578$SG4.1543@newsfe03.iad>
In reply to#5172
On 11-06-10 06:03 AM, Nigel Wade wrote:
> On 10/06/11 08:33, Andreas Leitgeb wrote:
>> Gene Wirchenko <genew@ocis.net> wrote:
>>>      I am writing a simple preprocessor.  I have a few spots where a
>>> string needs to be parsed.  I want to call something like this:
>>>           String ReturnString="";
>>>           boolean DidItWork=GetString(ReturnString);
>>>           if (!DidItWork)
>>>              // too bad
>>> It is not acceptable to have a special String value mean failure.  I
>>> want the method to be able to return any potential string.
>>
>> There's three basic ways to do it:
>>
>> 1) Return null to indicate failure. 
>>
>> 2) instead of the string, pass a mutable container of a string:
>>
>> 3) encode the String: e.g.: prepend a particular text to "success"-
> 
> Are 1) and 3) not precluded by the proviso "It is not acceptable to have
> a special String value mean failure".
> 
> A fourth way would be to return a class/object containing both the
> boolean and the String. To me, this would be the natural OO way of
> returning more information than a primitive type.
> 
> And a 5th way could be to return the String and throw an Exception if it
> did not work. Some purists may argue that failure to work is not
> strictly an exception, but if it gets the job done...
> 
This is the kind of thing where "purists" will get a bit bloody. Not to
teach you or any other respondent here how to suck eggs, but I'll throw
in, for general edification of a wider audience, the information that
we've got this problem both because Java has "pass object reference by
value" and Strings are immutable. Hence the OP's question.

Given that, Andreas' #2 is legit (I agree, Nigel, with your concerns
regarding #1 and #3), and so are the two suggestions you and Patricia
have put forth.

I'll accept that returning an object containing both the possible
modified String and a boolean status is OK. I don't much like it,
however, for two reasons. It's still the use of a return value for
operation status, and although that's defensible, there's nothing OO
about it - it's pure imperative programming. And were we to still pursue
that approach, unfortunately Java has no elegant means for supporting
it, unlike Haskell Maybe or Scala Option.

The failure of Java to cleanly support the previous approach pretty much
argues, IMHO, for exceptions. And this is, again IMHO, quite pure. It's
basically my business to define what I consider to be failures and
errors. Myself I see absolutely no problem in arguing that a failure to
work (parse) is a failure. :-) It's certainly an error in the input to
be parsed. In any case the OP would hardly be asking for an operation
success status if it wasn't possible for the method to fail.

Another argument for exceptions here is the OP's

if (!DidItWork)
    // too bad

bit. I have my doubts as to whether the OP's intended error processing
consists just of a NOOP and a comment. Assuming that it doesn't, and one
actually wants to do something productive in the error-handling,
exceptions are the best way to do it.

AHS

[toc] | [prev] | [next] | [standalone]


#5177

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2011-06-10 13:12 +0000
Message-ID<slrniv461g.phi.avl@gamma.logic.tuwien.ac.at>
In reply to#5175
Arved Sandstrom <asandstrom3minus1@eastlink.ca> wrote:
> I'll accept that returning an object containing both the possible
> modified String and a boolean status is OK. I don't much like it,

Why would such a returned object contain a possibly *modified* String?
It would expectably contain whatever String the method getString wants
the caller to see. It doesn't get one from outside in this case (as 
opposed to my #2 case), so there's nothing to "modify".

> however, for two reasons. It's still the use of a return value for
> operation status, and although that's defensible, there's nothing OO
> about it - it's pure imperative programming. And were we to still pursue
> that approach, unfortunately Java has no elegant means for supporting
> it, unlike Haskell Maybe or Scala Option.

Not sure, what feature you're principially talking of.  Is it some kind of 
syntactic sugar to further simplify code like this:

  BoolStr bs = getString();
  boolean b=bs.bool; String s=bs.str;

?
(just curious)

[toc] | [prev] | [next] | [standalone]


#5194

FromArved Sandstrom <asandstrom3minus1@eastlink.ca>
Date2011-06-10 15:44 -0300
Message-ID<8CtIp.4644$PA5.4578@newsfe01.iad>
In reply to#5177
On 11-06-10 10:12 AM, Andreas Leitgeb wrote:
> Arved Sandstrom <asandstrom3minus1@eastlink.ca> wrote:
>> I'll accept that returning an object containing both the possible
>> modified String and a boolean status is OK. I don't much like it,
> 
> Why would such a returned object contain a possibly *modified* String?
> It would expectably contain whatever String the method getString wants
> the caller to see. It doesn't get one from outside in this case (as 
> opposed to my #2 case), so there's nothing to "modify".

Sorry, my brain disconnected from my fingertips for a few seconds there.
Not "possible modified" String, but just result String. You're quite right.

>> however, for two reasons. It's still the use of a return value for
>> operation status, and although that's defensible, there's nothing OO
>> about it - it's pure imperative programming. And were we to still pursue
>> that approach, unfortunately Java has no elegant means for supporting
>> it, unlike Haskell Maybe or Scala Option.
> 
> Not sure, what feature you're principially talking of.  Is it some kind of 
> syntactic sugar to further simplify code like this:
> 
>   BoolStr bs = getString();
>   boolean b=bs.bool; String s=bs.str;
> 
> ?
> (just curious)

Maybe and Option are datatypes that allow you to return either the
requested value or a value that represents a failure of the computation.
This is conceptually different from having a special value, because in
the case of Maybe or Option, if the function/method succeeds, *every*
possible value of the underlying datatype (String or Integer or
whatever) is still a legal successful value. In effect Maybe and Option
are wrapper types just like BoolStr in your example; it's simply that
Scala and Haskell have better language support for dealing with
datatypes of that sort.

Like I said, in Java the "BoolStr" approach wouldn't be *my* preference
- I like exceptions here. But I wouldn't hold my nose if someone decided
to use "BoolStr".

AHS

[toc] | [prev] | [next] | [standalone]


#5244

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2011-06-12 16:29 +0000
Message-ID<slrniv9qag.phi.avl@gamma.logic.tuwien.ac.at>
In reply to#5194
Arved Sandstrom <asandstrom3minus1@eastlink.ca> wrote:
>>> however, for two reasons. It's still the use of a return value for
>>> operation status, and although that's defensible, there's nothing OO
>>> about it - it's pure imperative programming. And were we to still pursue
>>> that approach, unfortunately Java has no elegant means for supporting
>>> it, unlike Haskell Maybe or Scala Option.
>> Not sure, what feature you're principially talking of.  Is it some kind of 
>> syntactic sugar to further simplify code like this:
>>   BoolStr bs = getString();
>>   boolean b=bs.bool; String s=bs.str;
>
> In effect Maybe and Option
> are wrapper types just like BoolStr in your example; it's simply that
> Scala and Haskell have better language support for dealing with
> datatypes of that sort.

Yeah, I hoped you'd give a short example of use in Haskell/Scala, to show
what a language could make even simpler about that.

[toc] | [prev] | [next] | [standalone]


#5278

FromSilvio <silvio@moc.com>
Date2011-06-12 23:00 +0200
Message-ID<4df5290c$0$49183$e4fe514c@news.xs4all.nl>
In reply to#5244
On 06/12/2011 06:29 PM, Andreas Leitgeb wrote:
> Arved Sandstrom<asandstrom3minus1@eastlink.ca>  wrote:
>>>> however, for two reasons. It's still the use of a return value for
>>>> operation status, and although that's defensible, there's nothing OO
>>>> about it - it's pure imperative programming. And were we to still pursue
>>>> that approach, unfortunately Java has no elegant means for supporting
>>>> it, unlike Haskell Maybe or Scala Option.
>>> Not sure, what feature you're principially talking of.  Is it some kind of
>>> syntactic sugar to further simplify code like this:
>>>    BoolStr bs = getString();
>>>    boolean b=bs.bool; String s=bs.str;
>>
>> In effect Maybe and Option
>> are wrapper types just like BoolStr in your example; it's simply that
>> Scala and Haskell have better language support for dealing with
>> datatypes of that sort.
>
> Yeah, I hoped you'd give a short example of use in Haskell/Scala, to show
> what a language could make even simpler about that.
>

Well, here is an example in Scala:

Let's assume we have a getString defined as:

def getString(s : String) : Option[String] =
{
    if (s.reverse == s) Some(s.toLowerCase)
    else None
}

then it will return either Some(r) where r is a String or it will return 
None indicating failure.

We could call it like this:

val t : Option[String] = getString(s)

or a bit shorter:

val t = getString(s)

and let the compiler figure out the type of t (I could have dropped the 
Option[String] return type from the getString definition the same way).

Now we could use pattern matching against t:

t match
{
    case Some(r) => println("Success, return value is: " + r)
    case None => println("Failure")
}

However, since an Option[T] is a monad like most containers in Scala are 
we have shorthand notations for chaining operations on it like map, 
foreach, forall, exists etc.

Example1: t.map(_.length) will return an Option[Int] which is None if t 
is None or Some(r.length) if t is Some(r)

Example2: t.foreach(println(_)) will print r if t is Some(r) and do 
nothing if t is None.

Pattern matching is an incredible powerfull and flexible language 
feature in Scala and clearly lays out how Option[T] can be treated. In 
practice we rarely use it on an Option because the shorthand notations 
cover almost every practical use.

Gr. Silvio

[toc] | [prev] | [next] | [standalone]


#5279

FromSilvio <silvio@moc.com>
Date2011-06-12 23:06 +0200
Message-ID<4df52a61$0$49177$e4fe514c@news.xs4all.nl>
In reply to#5278
On 06/12/2011 11:00 PM, Silvio wrote:
> On 06/12/2011 06:29 PM, Andreas Leitgeb wrote:
>> Arved Sandstrom<asandstrom3minus1@eastlink.ca> wrote:
>>>>> however, for two reasons. It's still the use of a return value for
>>>>> operation status, and although that's defensible, there's nothing OO
>>>>> about it - it's pure imperative programming. And were we to still
>>>>> pursue
>>>>> that approach, unfortunately Java has no elegant means for supporting
>>>>> it, unlike Haskell Maybe or Scala Option.
>>>> Not sure, what feature you're principially talking of. Is it some
>>>> kind of
>>>> syntactic sugar to further simplify code like this:
>>>> BoolStr bs = getString();
>>>> boolean b=bs.bool; String s=bs.str;
>>>
>>> In effect Maybe and Option
>>> are wrapper types just like BoolStr in your example; it's simply that
>>> Scala and Haskell have better language support for dealing with
>>> datatypes of that sort.
>>
>> Yeah, I hoped you'd give a short example of use in Haskell/Scala, to show
>> what a language could make even simpler about that.
>>
>
> Well, here is an example in Scala:
>
> Let's assume we have a getString defined as:
>
> def getString(s : String) : Option[String] =
> {
> if (s.reverse == s) Some(s.toLowerCase)
> else None
> }
>
> then it will return either Some(r) where r is a String or it will return
> None indicating failure.
>
> We could call it like this:
>
> val t : Option[String] = getString(s)
>
> or a bit shorter:
>
> val t = getString(s)
>
> and let the compiler figure out the type of t (I could have dropped the
> Option[String] return type from the getString definition the same way).
>
> Now we could use pattern matching against t:
>
> t match
> {
> case Some(r) => println("Success, return value is: " + r)
> case None => println("Failure")
> }
>
> However, since an Option[T] is a monad like most containers in Scala are
> we have shorthand notations for chaining operations on it like map,
> foreach, forall, exists etc.
>
> Example1: t.map(_.length) will return an Option[Int] which is None if t
> is None or Some(r.length) if t is Some(r)
>
> Example2: t.foreach(println(_)) will print r if t is Some(r) and do
> nothing if t is None.
>
> Pattern matching is an incredible powerfull and flexible language
> feature in Scala and clearly lays out how Option[T] can be treated. In
> practice we rarely use it on an Option because the shorthand notations
> cover almost every practical use.
>
> Gr. Silvio
>

I should have said "short cuts" instead of "shorthand notations". They 
are not notational magic but simple library functions.

[toc] | [prev] | [next] | [standalone]


#5300

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2011-06-14 10:52 +0000
Message-ID<slrnivefbp.phi.avl@gamma.logic.tuwien.ac.at>
In reply to#5278
Silvio <silvio@moc.com> wrote:
> Well, here is an example in Scala:
>  [...]
> def getString(s : String) : Option[String] =
> {
>     if (s.reverse == s) Some(s.toLowerCase)
>     else None
> }
>  [...]
>  val t = getString(s)
>  [...]
> t match
> {
>     case Some(r) => println("Success, return value is: " + r)
>     case None => println("Failure")
> }

Ah, thanks.  Yep, I've seen this concept once when playing with 
OCaml (which mentions Haskell as one of its roots). Never got 
warm with it, though.

In the end, it isn't all that more concise than C++/Java...
It's a bit like C's unions with some byte ahead to tell which
of the variants is the current one, and bunch of logical operations
that is often trivially converted into a couple of (possibly nested)
"if-else"s.   I'm not saying it's bad, just it didn't impress me all
that much, so far.

[toc] | [prev] | [next] | [standalone]


#5303

FromSilvio <silvio@moc.com>
Date2011-06-14 17:13 +0200
Message-ID<4df77a95$0$49041$e4fe514c@news.xs4all.nl>
In reply to#5300
On 06/14/2011 12:52 PM, Andreas Leitgeb wrote:
> Silvio<silvio@moc.com>  wrote:
>> Well, here is an example in Scala:
>>   [...]
>> def getString(s : String) : Option[String] =
>> {
>>      if (s.reverse == s) Some(s.toLowerCase)
>>      else None
>> }
>>   [...]
>>   val t = getString(s)
>>   [...]
>> t match
>> {
>>      case Some(r) =>  println("Success, return value is: " + r)
>>      case None =>  println("Failure")
>> }
>
> Ah, thanks.  Yep, I've seen this concept once when playing with
> OCaml (which mentions Haskell as one of its roots). Never got
> warm with it, though.
>
> In the end, it isn't all that more concise than C++/Java...
> It's a bit like C's unions with some byte ahead to tell which
> of the variants is the current one, and bunch of logical operations
> that is often trivially converted into a couple of (possibly nested)
> "if-else"s.   I'm not saying it's bad, just it didn't impress me all
> that much, so far.
>

Actually instead of being union-like Some and None are best thought of 
as subclasses of Option (with None being an 'object' which is best 
described as a singleton class).

And you are right in saying that a pattern match on an Option is quite 
verbose, probably more verbose than a plain if-else.

I merely used it to lay out the logical structure of the Option. As I 
said Option variables are usually handled via methods like map/foreach/etc.
This is not only shorter and easier to read (for people used to the 
idiom) but it also mixes nicely with the way containers likes List, Map 
etc. work.

Only when used in combination with other monads does Option shine.

Pattern matching is very powerful because it unifies matching on types 
and values AND extracting sub-values from matched values. But it would 
deserve better examples than the one I provided.

One would have to consider a larger piece of code to appreciate it as a 
whole instead of looking at isolated language features.

Cheers,

Silvio

[toc] | [prev] | [next] | [standalone]


#5312

FromArved Sandstrom <asandstrom3minus1@eastlink.ca>
Date2011-06-14 17:58 -0300
Message-ID<_XPJp.2060$g12.487@newsfe20.iad>
In reply to#5303
On 11-06-14 12:13 PM, Silvio wrote:
> On 06/14/2011 12:52 PM, Andreas Leitgeb wrote:
>> Silvio<silvio@moc.com>  wrote:
>>> Well, here is an example in Scala:
>>>   [...]
>>> def getString(s : String) : Option[String] =
>>> {
>>>      if (s.reverse == s) Some(s.toLowerCase)
>>>      else None
>>> }
>>>   [...]
>>>   val t = getString(s)
>>>   [...]
>>> t match
>>> {
>>>      case Some(r) =>  println("Success, return value is: " + r)
>>>      case None =>  println("Failure")
>>> }
>>
>> Ah, thanks.  Yep, I've seen this concept once when playing with
>> OCaml (which mentions Haskell as one of its roots). Never got
>> warm with it, though.
>>
>> In the end, it isn't all that more concise than C++/Java...
>> It's a bit like C's unions with some byte ahead to tell which
>> of the variants is the current one, and bunch of logical operations
>> that is often trivially converted into a couple of (possibly nested)
>> "if-else"s.   I'm not saying it's bad, just it didn't impress me all
>> that much, so far.
>>
> 
[ SNIP ]

> Only when used in combination with other monads does Option shine.
> 
> Pattern matching is very powerful because it unifies matching on types
> and values AND extracting sub-values from matched values. But it would
> deserve better examples than the one I provided.
> 
> One would have to consider a larger piece of code to appreciate it as a
> whole instead of looking at isolated language features.

+1.

Either larger chunks of code, and/or chaining of operations. With Option
or Maybe, you don't have to check every intermediate result. With
idiomatic Haskell or Scala you'd probably not see a whole bunch of
pattern matching for Maybe or Option at all.

It's way more concise than Java, and another advantage still remains
that we're not looking for a special value (null).

> Cheers,
> 
> Silvio

AHS

[toc] | [prev] | [next] | [standalone]


#5313

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2011-06-14 21:18 +0000
Message-ID<slrnivfk13.phi.avl@gamma.logic.tuwien.ac.at>
In reply to#5312
Arved Sandstrom <asandstrom3minus1@eastlink.ca> wrote:
> It's way more concise than Java, and another advantage still remains
> that we're not looking for a special value (null).

I'm not yet sure, whether null in Java counts as a "String value", or not.

I think it is not (whereas the empty string of course is). As such, a 
variable (or field) "s" (or even an expression) of type String really
happens to be implicitly the pendant of Haskell's "Option"al String:

Either it is "Null"... (ahem, "null"), or it holds an actual String value.

Ditto for all the non-primitive types.

[toc] | [prev] | [next] | [standalone]


#5315

FromArved Sandstrom <asandstrom3minus1@eastlink.ca>
Date2011-06-14 20:14 -0300
Message-ID<6XRJp.10628$5v5.8742@newsfe11.iad>
In reply to#5313
On 11-06-14 06:18 PM, Andreas Leitgeb wrote:
> Arved Sandstrom <asandstrom3minus1@eastlink.ca> wrote:
>> It's way more concise than Java, and another advantage still remains
>> that we're not looking for a special value (null).
> 
> I'm not yet sure, whether null in Java counts as a "String value", or not.
> 
> I think it is not (whereas the empty string of course is). As such, a 
> variable (or field) "s" (or even an expression) of type String really
> happens to be implicitly the pendant of Haskell's "Option"al String:
> 
> Either it is "Null"... (ahem, "null"), or it holds an actual String value.
> 
> Ditto for all the non-primitive types.
> 
I know what you're saying, but the JLS says that a variable of a class
type can hold a null reference or a reference to an object whose type is
that class type or any subclass of that class type. There are similar
comments for variables of interface and array types.

The JLS also says that the null reference can be cast to any reference
type. The JLS says that we can pretend that 'null' is a special literal
that can be of any reference type.

Furthermore, the default value for all reference types is null.

All that JLS language - but particularly that last statement from the
JLS - tells me that we consider 'null' to be a permitted value of
reference types. A String variable can refer to 'null' just as it can
refer to "" or "Arved", so from that perspective 'null' is a String
value; albeit a special one.

It's not the same notion as Option or Maybe, although I believe I sense
what you were getting at. The difference being, if I were to use, as an
example, Option[java.lang.String] in Scala, legitimate values of a
variable of that type would be

Some("Arved")
Some(null)
None

That is, Scala Option is like a container. "Some" means that a value of
a certain type (like java.lang.String) is contained; "None" means that
the container is empty. In the case of Scala Option, a reference value
contained by Some may be 'null' - this is qualitatively not the same
thing as None.

AHS

[toc] | [prev] | [next] | [standalone]


#5321

FromArved Sandstrom <asandstrom3minus1@eastlink.ca>
Date2011-06-15 07:13 -0300
Message-ID<ZA%Jp.14463$8G4.10041@newsfe17.iad>
In reply to#5315
On 11-06-14 09:09 PM, Stefan Ram wrote:
> Arved Sandstrom <asandstrom3minus1@eastlink.ca> writes:
>> refer to "" or "Arved", so from that perspective 'null' is a String
>> value; albeit a special one.
> 
>   The JLS does not defined »String value«, so you are all free to
>   define it as you like to. However, we also have
> 
> !( null instanceof java.lang.String )
> 
>   . Since the objects of a value class are intended to model the
>   values modulo »equals«, not being an instance of such a class
>   has some weight in favor of not being a value of that model.
> 
>   Albeit in some other context, the JLS says with regard to
>   Annotations,
> 
>       »Note that null is not a legal element value for any
>       element type.«
> 
>   null surely is a /reference value/, but it does not identify
>   a string value in the sense of the class String as a class
>   whose instances model string values.
> 
I agree with the statements above, sure. The problem we have is that
'instanceof', say, indicates that 'null' is not an instance of a
reference type like String. But we also have that Java variables of
reference type can be assigned the value 'null' (implicit typecast).

So we end up with a situation where IMHO it's probably advisable not to
try making too much sense of it. The language mechanics have placed us
in the position of accepting that one special value that you can assign
to variables of reference type is _not_ an instance of any reference
type, but can be somehow implicitly typecast to any reference type. If
one ventures (perhaps too far) down this road, one might ask, what is
the implicit special value of String that null is implicitly typecast
_to_, that is nonetheless not an instanceof String?

Down that road lies madness. Hence the JLS' suggestion that programmers
treat null as a special literal that *can be of any reference type*. And
so I treat it, regardless of the behaviour of 'instanceof'.

We also have the difficulty in Java that 'null' appears - frequently -
as a working - albeit "special" - value of reference variables in
programs. People use it to mean uninitialized, unknown, a termination
condition, and I return also to the fact that 'null' is the *default*
value assigned to reference type variables.

Having said all this, let me revisit Option and Maybe. For me the
distinction to be drawn between the *semantics* of Option/Maybe and the
nullability of Java reference-type variables is probably one of degree,
not kind. So I regret using the word "qualitatively" in my previous
post; I'm not sure what word I prefer in its stead :-). Option/Maybe are
clean and unambiguous types that represent, by design, optional values
of some contained type. The interpretation of 'null' in Java is not so
clean. Furthermore, I can use == and != with 'null' in constructs like

"Arved" != null

just as easily as

"Arved" == "Bill"

which to me further blurs the perception that null is, or isn't,
_effectively_ a value of String or any other reference type. Again, the
JLS suggestion that we pretend that that's what 'null' is.

To return to Andreas' argument, it's certainly possible for any given
Java programmer to rigorously adhere to an interpretation of 'null' as
meaning None or Nothing. That would however be a personal choice; some
other programmer might not do that (it could be Unknown, or No Mapping
For Key X, or End Of Stream). Assuming that None/Nothing is the rigorous
interpretation of 'null' by said programmer, there is still no special
treatment for the 'null' value...we end up testing for it the same way
as we do for object instances. We test for it just like we do for any
other value, but arguably it's special. So special that it's not an
instance of any reference type except the null type.

So I'll stick to the main case, which is simply that Scala option and
Haskell Maybe are better ways of dealing with this notion. In fact so
would BoolStr (or BoolObj) be; Nigel's suggestion. In Java, as I've
expressed, I prefer exceptions anyway, but I absolutely don't like
'null' as a special value (of something) (*). The OP in any case said
that that latter approach will not be acceptable.

AHS

* I'll hold my nose and use it - Java makes it difficult not to.

[toc] | [prev] | [next] | [standalone]


#5322

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2011-06-15 12:50 +0000
Message-ID<slrnivhakt.phi.avl@gamma.logic.tuwien.ac.at>
In reply to#5321
Arved Sandstrom <asandstrom3minus1@eastlink.ca> wrote:
> On 11-06-14 09:09 PM, Stefan Ram wrote:
>>   null surely is a /reference value/, but it does not identify
>>   a string value in the sense of the class String as a class
>>   whose instances model string values.

Yeah, Stefan, that's just how I see it.  There's a distinction between
reference values and "values"/objects of the particular instance/class
type.

Unless Scala also has a concept for   Some(null)   (I do *not* mean
Some(None), as that would then be two Option-layers), we can say
that Java's references are a stock "Option" wrapper for the actual
values. Any further Option layers in Java would not look that simple,
but require some explicit container-object, like a singleton-array or
a custom one-field class's instance.

[toc] | [prev] | [next] | [standalone]


#5326

FromArved Sandstrom <asandstrom3minus1@eastlink.ca>
Date2011-06-15 18:52 -0300
Message-ID<JQ9Kp.128$tB1.119@newsfe19.iad>
In reply to#5322
On 11-06-15 09:50 AM, Andreas Leitgeb wrote:
> Arved Sandstrom <asandstrom3minus1@eastlink.ca> wrote:
>> On 11-06-14 09:09 PM, Stefan Ram wrote:
>>>   null surely is a /reference value/, but it does not identify
>>>   a string value in the sense of the class String as a class
>>>   whose instances model string values.
> 
> Yeah, Stefan, that's just how I see it.  There's a distinction between
> reference values and "values"/objects of the particular instance/class
> type.
> 
> Unless Scala also has a concept for   Some(null)   (I do *not* mean
> Some(None), as that would then be two Option-layers), we can say
> that Java's references are a stock "Option" wrapper for the actual
> values. Any further Option layers in Java would not look that simple,
> but require some explicit container-object, like a singleton-array or
> a custom one-field class's instance.
> 
You can do Some(null) in Scala; I mentioned that already in a previous
post. That's an entirely expected behaviour of Option; as far as it's
concerned 'null' is a valid value, just like any other, of the reference
type that it contains.

_You_ can consider Java references to be stock "Option" wrappers for
actual values, sure. It won't hurt anyone if you do. I'm not going to
myself, because unlike Option and Maybe, Java reference types are _not_
wrappers, and the way the language is, 'null' is a legitimate actual
value *of* a reference type variable. There's no wrapping involved. We
happen to ascribe various meanings to this special value, depending on
usage and API, but it's still a value *of* a reference type variable.

AHS

[toc] | [prev] | [next] | [standalone]


#5325

Fromlewbloch <lewbloch@gmail.com>
Date2011-06-15 07:06 -0700
Message-ID<e8f4d2f3-ebb8-422d-8dd6-c4e803311ff6@h12g2000pro.googlegroups.com>
In reply to#5313
On Jun 14, 2:18 pm, Andreas Leitgeb <a...@gamma.logic.tuwien.ac.at>
wrote:
> Arved Sandstrom <asandstrom3min...@eastlink.ca> wrote:
> > It's way more concise than Java, and another advantage still remains
> > that we're not looking for a special value (null).
>
> I'm not yet sure, whether null in Java counts as a "String value", or not.
>
> I think it is not (whereas the empty string of course is). As such, a
> variable (or field) "s" (or even an expression) of type String really
> happens to be implicitly the pendant of Haskell's "Option"al String:
>
> Either it is "Null"... (ahem, "null"), or it holds an actual String value.
>
> Ditto for all the non-primitive types.

'null' is an out-of-band 'String' value (or any other reference type).

I use the "is-a {type}" to indicate if assignment (or casting) is
permissible.  'String x = null;' is valid, so 'null' is a 'String' (or
any other reference type) value.  It is "out of band", which expresses
the "not-a" concept well enough to write good software.

--
Lew

[toc] | [prev] | [next] | [standalone]


#5327

FromMichael Wojcik <mwojcik@newsguy.com>
Date2011-06-15 21:33 -0400
Message-ID<itbmhc117f9@news3.newsguy.com>
In reply to#5300
Andreas Leitgeb wrote:
> Silvio <silvio@moc.com> wrote:
>> Well, here is an example in Scala:
>>  [...]
>> def getString(s : String) : Option[String] =
>> {
>>     if (s.reverse == s) Some(s.toLowerCase)
>>     else None
>> }
>>  [...]
>>  val t = getString(s)
>>  [...]
>> t match
>> {
>>     case Some(r) => println("Success, return value is: " + r)
>>     case None => println("Failure")
>> }
> 
> Ah, thanks.  Yep, I've seen this concept once when playing with 
> OCaml (which mentions Haskell as one of its roots). Never got 
> warm with it, though.

They both get it from ML, which AFAIK is the first programming
language in that particular family. It introduced the type inference
and matching features that you find in OCaml (which is the OO version
of Caml, a ML dialect), Haskell, Scala, F# (which is basically OCaml
adapted for .NET), etc.

In the Verona of functional languages, the ML family are the Montagues
to the LISP family's Capulets. Or something like that.

-- 
Michael Wojcik
Micro Focus
Rhetoric & Writing, Michigan State University

[toc] | [prev] | [next] | [standalone]


Page 1 of 5  [1] 2 3 4 5  Next page →

Back to top | Article view | comp.lang.java.programmer


csiph-web