Tuesday, January 20, 2015

Give Up The func

There is a Thing about learning new languages - it tends to make you Think Differently.

I've written a lot of perl and Java over the years & so it took me a while to get the whole Functional Programming thing...

It basically took me learning Swift.

That being said - I don't write Swift code for a living.

As a result there strange new ideas have been seeping out into my perl & Java code.

I recently found myself, for example, emulating functional programming in Java by using an Enum as a return-type which would trigger a variety of different methods with a switch statement.  

Each different element of the Enum is treated as a case inside the switch.  

Then for the last line of the switch I added:
throw new AssertionError(this.name());

Which is essentially the compiler saying "WTF?"...

Admittedly this is, at best, a very weak example of Functional Programming - but I'm not here to demonstrate the Java implementation of a Closure - others have done that far better than I could.

The point of this is that simply that rather than limiting myself to the constraints of managing a return-type - that type itself might reflect a relationship to varied behavior.

Does that mean that we can pass around references to functions?  Not exactly, but usually what you are trying to accomplish can still be done with some code contortionism.

Loose functions are simply methods in Java so an Enum of triggers could fire cases in a switch, all of which behave differently & call various methods.

Depending on what data those methods need to access dictates if they are Class methods or if you need to define a Class to generate object instances.
 




Wednesday, January 14, 2015

Old Dog Learns New Trick: The NCO

While learning Swift I came across something to which I was not accustomed: the Nil Coalescing Operator.


For example:
optionalValue ?? valueIfNil

Which more or less translates to: "The value of optionalValue unless it isn't defined, in which case default to valueIfNil"

Usually this would be written as:
(optionalValue != nil) ? optionalValue! : valueIfNil;

I liked what I saw & looked into it and to my surprise it also exists in perl as the Null Coalescing Operator / Logical Defined-Or operator.

In perl the above example is rewritten as:

$optional_value // $value_if_null

Which is in turn shorthand for:
defined($optional_value) ? $optional_value : $value_if_null

However there is more - because in perl there is a shorthand notation for this:
$optional_value //= $value_if_null
  
Which is the equivalent of:
$optional_value = $optional_value // $value_if_null

Tuesday, January 13, 2015

How to utf8 with perl

I have had a good deal of trouble working with utf8 with perl scripts.

It is extremely easy to mess things up - in fact all you have to do try to add two strings together (aka concatenate).

As such I have had to come up with a simplified solution for my team.

I will share:



#!/usr/bin/perl

use open qw( :std :locale );
use Encode qw(decode is_utf8);

my $a = "\xc2\xa9\xc2\xae\xe2\x84\xa2";
my $b = "Any old thing.";

print "a:",$a,"\n";
print "b:",$b,"\n";

my $c = jibe($a,$b);
print "c:",$c,"\n";

sub jibe {
  my($s,$t) = @_;
  my $r = join('', (is_utf8($s)?$s:decode('utf8',$s)), (is_utf8($t)?$t:decode('utf8',$t)));
  return $r;
}

And the output is:

$ perl ./simple_utf8.pl
a:©®�
b:Any old thing.
c:©®™Any old thing.


The key thing here is that the jibe sub will allow you to safely concatenate two strings and produce a proper utf8 result.

If you include the use statements and the jibe subroutine you can use this in your code.

It is designed to analyze your input & only decode as necessary - so it gives you a bit more license to mix & match input strings.

Monday, January 5, 2015

!2Swift:Of lumpy carpets & loose wires...

Welcome to the newly branded !2Swift (not-too-swift) branch of my blog.

Since I have been talking about just about nothing else besides Swift for days on end it seems fitting that I make a *thing* out of it...

But let's be real now for a moment: I am neither a zealot/fanboi nor am I a hater/assassin.  

I am a Skeptical Software Developer.

It is difficult to keep your politics out of your code these days as we have to endure endless wrangling over licenses.  To be politically neutral is to be intentionally clueless.

I am therefore going out of my way to behave in the way that I have seen many old people use to good effect:  I am filtering out things-I-don't-want-to-hear and only focusing on the interesting parts.


"Adapt what is useful, reject what is useless, and add what is specifically your own" - Bruce Lee

But that also means that I sometimes, just out of pragmatism, I will have to point to things & say "WTF?"

One of those things is the Coccoa framework.  There was a serious WTF moment that I experienced when switching gears from trying to learn Swift to finding the state of affairs that is the Core Libraries we need to depend upon in order to write *Everything*.

 I will provide further examples in coming posts, but looking below to my cargo cult posting about accessing files - you can see some hints there to the wires hanging out of the back and they are all of the ObjectiveC variety. (Anything with the 'NS' prefix for example)

You will come up against this every time you cross the language barrier in terms of features.  For example, in Using Swift with Coccoa and Objective-C in the section on Working with nil it points out that ObjC works with raw pointers that could be NULL.  Swift however guarantees all values are non-nil.  Thus Swift wraps the class-types in imported ObjC API's in an implicitly unwrapped optional type.  So before you use an ObjC object you need to check that it is not missing.

In their example when importing this ObjectiveC method:

- (NSDate *)dueDateForProject:(Project *)project;

You have to do this in Swift:

func dueDateForProject(project: Project!) -> NSDate! 

So you might be thinking either:
  1. WTF? ::facepalm::
  2. What's the big deal?
And to you in the second group I will point out this simple truth:
Everything that you want to do requires that you import ObjectiveC code.


[EDIT: It was pointed out that I should explain my point a little further if I am not going to force people to Do The Work to get it...]


The Big Deal is the '!' at the end.  Whenever you use them you are essentially bypassing the safety built into the language.  This is a crash waiting to happen every time that you do it & these frameworks require that we do it all over the place.

Saturday, January 3, 2015

Java <-> Swift : a Niche Market?

If you followed along at all with the last post then you probably have some programming chops.

I'm going to keep up my journey of learning Swift for as long as I can.  These things have a way of running out of gas after a good long binge - usually when life catches up & starts demanding that you spend time paying attention to all of the things you have been neglecting in order to do heads-down-programming.

That being said, while I know many, many programming languages already, the two that I have been paid to write the most often have been Java and perl.

One thing that I have often lamented was the complete culture clash that existed between those two communities.  I could never fathom it since both communities purported to have the same goal: i.e. a cross-platform programming language.

Now that I've drunk enough Apple Kool-Aid to start sweating the stuff out of my pores I can truthfully say that I am *not* over the fact that Swift is completely inwardly-facing with regards to the Apple technology stack.  This is a major failing & it will dog this technology for as long as they continue to behave this way.

But I am determined not to let that fact keep me out in the cold again.  I made this mistake once with ObjectiveC already.

So what immediate benefit can I provide?  That is, if I wanted to get paid today to add value with the Swift language, what could I do?

Well the simple answer is that I can provide Java/Swift conversion services.  I am fully fluent in Java and I am coming up to speed on Swift as quickly as I can.  What I find interesting is that, as in many other languages, you can use the Java style when writing code.  What that amounts to is class-based namespaces and encapsulated functions that only return a single data type.

But how would you go the other way?  That is from Swift to Java?  The simple answer as I mentioned in the prior post is to make liberal use of Tuple as a return type.  Also you will want to have basic default 'Global' class to contain any standalone functions as class methods. 

What this amounts to is that people will end up falling into camps : those who regularly port to other platforms and those who choose to write in idiomatic Swift.  

The latter camp will predictably be snobs & will do everything possible to break external compatibility.  

That isn't me throwing rocks at Apple, merely at language zealots - because this pattern has been replayed in any language that you can mention during its adoption cycle.

What is all of this talk about writing code for other platforms?  If you are actually planning on releasing a "Mobile Application" and think that iOS is "enough" - then you're missing at least half of the potential market for your app.

THAT more than anything is the main reason to resent Apple's decisions regarding Swift - but as I have pointed out before - resentment can be overcome with tolerance.

Friday, January 2, 2015

A cup full of Swift for Java Programmers

I am imbibing the Apple Kool-Aid.  

I have upgraded from a shot-glass to a coffee cup.

I'm just going to jump in here today with an example of a function so that we can compare the method signature of a Java method with a function in Swift:

//for your playground
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
    
    return (min, max, sum)
}
let statistics = calculateStatistics([5, 3, 100, 3, 9])
statistics.sum
statistics.2


The first line right away there's the keyword func.

This is necessary since a function can be defined as a standalone thing without the OOP-fetish containing object that Java requires.

Then we have a name, done in camelCapsStyle.

Then we have the input signature which (can have two names, one for internal & one for external use but) in this example only has one name "scores" which is an array of type Int.

Then there's the -> symbol which denotes the Output.

And in this example we see that Swift allows you to return multiple named values inside a Tuple.

Then there is the code block inside of the {} brackets which explains how that output comes to be.

The last 3 lines are specifically for your playground - the first calls the function with an array of sample data to construct the reply, the second references one of the returned output values by name and the last line returns the same value by index value of the returned tuple.

In java the method signature would look something like:

public Tuple calculateStatistics(int[] scores){}

And you would have to know to decode the 3 values in that returned Tuple without any hints. 

This method would need to exist inside some kind of container object, if only for namespace considerations.

More likely you would create 3 distinct methods, one for minimum, one for maximum and one for average and if you really needed the Tuple then a third method which would in turn call the first three.

All of that is of course still possible, but the point is that it is no longer necessary since Swift gives you this flexibility.