6 kyu

Binding within the List Monad

350 of 1,129user578387

Description:

In Haskell, Monads are simple containers, or even 'box-like' datastructures, of which lists are included, which can respond to certain functions, which are defined in the Monad typeclass. (To put it simply!)

In this kata, you must implement the Bind function for lists, or arrays. In haskell, the function is represented by >>=, but we'll just call it bind.

Essentially, bind should map the array with the function given, and then flatten it one time. Don't manipulate the original array; make you function pure: without side-effects, so that no variables are edited whilst the function is carried out. In dynamically typed languages, you should throw an error if the given function does not return a list.

Here's how it should work:

bind( [1,2,3], (a) -> [a+1] )
=> [2,3,4]

bind( [1,2,3], (a) -> [[a]] )
=> [[1],[2],[3]]

bind( [1,2,3], (a) -> a )
=> # ERROR! The returned value is not a list!
bind( [1,2,3], function(a){ return [a+1] } )
=> [2,3,4]

bind( [1,2,3], function(a){ return [[a]] } )
=> [[1],[2],[3]]

bind( [1,2,3], function(a){ return a } )
=> # ERROR! The returned value is not a list!
bind( [1,2,3], lambda a: [a+1] )
=> [2,3,4]

bind( [1,2,3], lambda a: [[a]] )
=> [[1],[2],[3]]

bind( [1,2,3], lambda a: a )
=> # ERROR! The returned value is not a list!
bind( [1,2,3] ) {|a| [a+1] }
=> [2,3,4]

bind( [1,2,3] ) {|a| [[a]] }
=> [[1],[2],[3]]

bind( [1,2,3] ) {|a| a }
=> # ERROR! The returned value is not a list!
(bind [1 2 3]  #(do [(+ % 1)]) )
=> [2,3,4]

(bind [1 2 3]  #(do [[ % ]]) )
=> [[1],[2],[3]]

(bind [1 2 3]  #(do %) )
=> # ERROR! The returned value is not a list!
bind(Arrays.asList(1,2,3), i -> Arrays.asList((int)i + 1))
//=> [2,3,4]

bind(Arrays.asList(1,2,3), i -> Arrays.asList(Arrays.asList(i)));
//=> [[1],[2],[3]]

bind(Arrays.asList(3,4,5), i -> i);
//=> # ERROR! Java does this on its own! You can't even compile! Strong typing FTW!

As per usual, the ruby function will be passed a Proc or Lambda. Remember that the function still takes two arguments!

Monads
Lists
Algorithms

Stats:

CreatedNov 20, 2014
PublishedDec 10, 2014
Warriors Trained2654
Total Skips686
Total Code Submissions6906
Total Times Completed1129
JavaScript Completions350
CoffeeScript Completions26
Ruby Completions106
Python Completions454
Java Completions259
Total Stars56
% of votes with a positive feedback rating89% of 171
Total "Very Satisfied" Votes137
Total "Somewhat Satisfied" Votes29
Total "Not Satisfied" Votes5
Ad
Contributors
  • user578387 Avatar
  • jhoffner Avatar
  • Azuaron Avatar
  • flaco Avatar
  • FArekkusu Avatar
Ad