Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: Working With Arrays

  1. #1
    Join Date
    Feb 2007
    Location
    🌎
    Posts
    528
    Thanks
    10
    Thanked 10 Times in 10 Posts
    Blog Entries
    2

    Default Working With Arrays

    I n̶e̶e̶d̶ want help.
    I am working on a [rather complicated] JavaScript.
    I need help with the following stages:
    STAGE 4
    Divide characters in a string into array values.
    For example, if I have (this is done with PHP):
    Code:
    var word1 = "animal";
    then it would make:
    Code:
    var array1 = new Array('a','n','i','m','a','l');
    STAGE 5
    Do something for all the values.
    For example:
    Code:
    if (array1[0] == array2[0]) {
    //do something
    }
    if (array1[1] == array2[1]) {
    //do the same thing
    }
    What I am asking is if it is possible to repeat this same thing for array.length.
    The arrays will be the same length.

    Another thing is if it is possible to just see if there are two values in the arrays that are the same and return them as variables, like:
    Code:
    var inarray1 = 2;
    var inarray2 = 6;
    if
    Code:
    var array1 = new Array('a', 'b', 'c', 'd');
    var array2 = new Array('x', 'f', 's', 'y', 'l', 'w', 'q', 'c', 'i');
    Note that if this occurs multiple times, I want it to use the first time.
    ....(o_ Penguins
    .---/(o_- techno_racing
    +(---//\-' in
    .+(_)--(_)' The McMurdo 500

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    The first is String.prototype.split():
    Code:
    var array1 = word1.split("");
    The third:
    Code:
    var Functional = {
      map: function(f, a) {
        for (var i = 0, n = a.length, r = []; i < n; ++i)
          r[i] = f(a[i], i);
    
        return r;
      },
    
      filter: function(f, a) {
        for (var i = 0, r = []; i < a.length; ++i)
          if (f(a[i], i))
            r[r.length] = a[i];
    
        return r;
      },
    
      compose: function(/* f1 [, f2 [, ... [, fn]]] */) {
        var fs = Array.prototype.slice.call(arguments);
    
        return function() {
          var args = Array.prototype.slice.call(arguments);
    
          for (var i = fs.length - 1; i >= 0; --i)
            args.unshift(fs[i].apply(this, args));
    
          return args[0];
        };
      },
    
      flip: function(f) {
        return function(a, b) {
          return f.call(this, b, a);
        };
      },
    
      curry: function(f, l, a) {
        l = (typeof l === "number" ? l : (f.length || 0));
        a = a || [];
    
        return function() {
          var m = a.concat(Array.prototype.slice.call(arguments));
          return m.length < l ? Functional.curry(f, l, m) : f.apply(this, m);
        };
      },
    
      Operators: {
        lookup: function(a, i) {
          return a[i];
        },
    
        equals: function(a, b) {
          return a === b;
        }
      }
    };
    
    var parallels = (function(F, O) {
      return function(a1, a2) {
        return F.filter(F.compose(O.equals, F.flip(F.curry(O.lookup, 2)(a2))), a1);
      };
    })(Functional, Functional.Operators);
    And the second, using the same Functional object as above:
    Code:
    function doForAllParallels(a1, a2, f) {
      return Functional.map(function(v, k) {
        if (a2[k] === v)
          return f(v, k);
      }, a1);
    }
    Last edited by Twey; 08-18-2008 at 06:51 PM.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. The Following User Says Thank You to Twey For This Useful Post:

    techno_race (08-20-2008)

  4. #3
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default

    I have a couple questions, Twey.

    In flip you have f.call(this, b, a); instead of f(b, a); Is that so it is compatable with method calls?

    I'm curious about your compose function. Even though I understand what it does, it seems a little unconventional to keep a history of old arguments. Why do you do that? I see the use of it in your parallels function to pass both args to a binary function, but in general, is your compose function more useful than an ordinary one?

    I personally define compose as
    Code:
    Function.prototype.o = function(g) {
      var f = this;
      return function() {
        return f(g.apply(null, arguments));
      };
    };
    
    // eg: var k = f. o (g). o (h);
    Also, how about
    Code:
    function doForAllParallels(f, a1, a2) {
      return Functional.map(f, parallels(a1, a2));
    }
    
    // var doForAllParallels = (function(F) {
    //   return F.compose( F.curry(F.map)(f), parallels );
    // })(Functional);
    PS: It would be cooler if all the functions in Functional were curried to begin with!

    Edit: I'm not sure, but I think var fs = Array.prototype.slice.call(arguments); can be simplified to var fs = arguments;
    Trinithis

  5. #4
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    In flip you have f.call(this, b, a); instead of f(b, a); Is that so it is compatable with method calls?
    More or less. It's so that if somehow a context gets passed to the wrapper function, it will be passed through transparently, as would be expected, rather than being lost, which is what would otherwise happen.

    This isn't actually the version of flip() in my toolkit, I revised it but the revision isn't beneficial here: it's now:
    Code:
        reorder: function(f, ord) {
          return function() {
            return f.apply(this, F.map(F.curry(O.lookup, 2, [arguments]), ord));
          };
        },
    
        flip: function(f) {
          return F.reorder(f, [1, 0]);
        },
    I'm curious about your compose function. Even though I understand what it does, it seems a little unconventional to keep a history of old arguments.
    Unconventional only from a Haskell perspective. In JS, I discovered as I was writing this, things are not quite so simple, due to every function taking a variable number of arguments. In addition, this is quite a non-Haskelly solution: in Haskell it would probably be preferable to do something like this:
    Code:
    parallels :: (Eq a) => [a] -> [a] -> [a]
    parallels [] _ = []
    parallels _ [] = []
    parallels (x:xs) (y:ys) =
      if x == y then
        x : (parallels xs ys)
      else
        parallels xs ys
    (that is to say,
    Code:
    function parallels(xs, ys) {
      if (!xs.length || !ys.length)
        return [];
    
      if (x === y)
        return [xs[0]].concat(parallels(xs.slice(1), ys.slice(1)));
    
      return parallels(xs.slice(1), ys.slice(1));
    }
    ) ... but recursion is generally discouraged in JS, since there's no optimisation for it and a fairly small stack.
    Also, how about [implementing doForAllParallels in terms of map?]
    Doesn't preserve keys, which was an implicit requirement. I almost wrote a filterStatic() and mapStatic() in which to implement it, but didn't in the end.
    PS: It would be cooler if all the functions in Functional were curried to begin with!
    Considered it already, but rejected on the grounds of performance.
    Last edited by Twey; 08-18-2008 at 09:11 PM. Reason: reorder() tweak.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  6. The Following User Says Thank You to Twey For This Useful Post:

    Trinithis (08-18-2008)

  7. #5
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default

    I'm guessing xxxStatic is like its xxx variant but throws Maybe (or something similar) into the mixture?
    Trinithis

  8. #6
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Well, for a given definition of Maybe:
    Code:
    function maybe(val, isNothing) {
      return isNothing ? undefined : val;
    }
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  9. #7
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default

    I wrote this a while ago:
    Code:
    function Maybe(val, isJust) {
      this.fromJust = val;
      this.isJust = isJust;
    }
    
    Maybe.unit = Just;
    
    Maybe.prototype = {
      bind: function(f) {
        return this.isJust
          ? f(this.fromJust)
          : Nothing
          ;
      },
      then: function(m) {
        return this.bind(function() {
          return m;
        });
      },
      toString: function() {
        return "[object Maybe]";
      }
    };
    
    function Just(val) {
      return new Maybe(val, true);
    }
    
    var Nothing = new Maybe(undefined, false);
    As of late, I've been trying to figure out a user-friendly way to implement type classes in such a way that types can be inferered along the way with a little help. So far, all my ideas have turned out to be somewhat painful. But if I succeed, then I can truly implement a monad typeclass, which would be cool.
    Last edited by Trinithis; 08-18-2008 at 09:22 PM. Reason: nevermind... there was no bug
    Trinithis

  10. #8
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Not bad, not bad. I would maybe do it a little differently if we're going for elegance rather than efficiency:
    Code:
    var Maybe = (function() {
      function Maybe(val) {
        if (val === undefined)
          return Nothing;
        else
          return Just(val);
      }
    
      function Nothing() {
        return Nothing;
      }
    
      Nothing.toString = function toString() {
        return "Nothing";
      };
    
      Nothing.bind = function bind(f) {
        return Nothing;
      };
    
      Nothing.then = function then(f) {
        return Nothing;
      };
    
      function Just(val) {
        function Just() {
          return Just;
        }
    
        Just.fromJust = function fromJust() {
          return val;
        };
    
        Just.toString = function toString() {
          return "Just " + val;
        };
    
        Just.bind = function bind(f) {
          return _Just(f(val));
        };
    
        Just.then = function then(f) {
          return _Just(f());
        };
    
        return Just;
      }
    
      var _Just = Just;
    
      return Maybe;
    })();
    Chris / chrisdone / la .xris. wrote a somewhat clumsy implementation of State in JS: http://chrisdone.com/stuff/javascrip...-monad.js.html.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  11. #9
    Join Date
    May 2007
    Location
    USA
    Posts
    373
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Default

    Interesting take. There's one thing I like in mine over yours . . . Maybe governs bind instead of the individual constructors. Also, yours doesn't allow a Just undefined.

    Never knew the following syntax was legal:
    Code:
    Nothing.bind = function bind(f) {
      return Nothing;
    };
    I saw that State implentation before when googling monads in javascript. I didn't like it.
    Trinithis

  12. #10
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    There's one thing I like in mine over yours . . . Maybe governs bind instead of the individual constructors.
    That's one of the things I disliked It seems neater to split it up. Consider the Haskell implementation (paraphrased, sorry):
    Code:
    Nothing >>= _ = Nothing
    (Just x) >>= f = f x
    Clearly separate.
    Never knew the following syntax was legal:
    I have an inhibition against using it. I very vaguely remember seeing somewhere that it was very slow. However, as the disclaimer says, it's elegance not efficiency, so I thought I may as well.
    Also, yours doesn't allow a Just undefined.
    Well, that's easy enough to solve:
    Code:
    var Maybe = (function() {
      function Maybe(val) {
        if (!arguments.length)
          return Nothing;
        else
          return Just(val);
      }
    
      function Nothing() {
        return Nothing;
      }
    
      Nothing.toString = function toString() {
        return "Nothing";
      };
    
      Nothing.bind = function bind(f) {
        return Nothing;
      };
    
      Nothing.then = function then(f) {
        return Nothing;
      };
    
      function Just(val) {
        function Just() {
          return Just;
        }
    
        Just.fromJust = function fromJust() {
          return val;
        };
    
        Just.toString = function toString() {
          return "Just " + val;
        };
    
        Just.bind = function bind(f) {
          return _Just(f(val));
        };
    
        Just.then = function then(f) {
          return _Just(f());
        };
    
        return Just;
      }
    
      var _Just = Just;
    
      return Maybe;
    })();
    To create a Nothing:
    Code:
    Maybe()
    To create a Just undefined:
    Code:
    Maybe(undefined)
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •