Composistion in SML (Discreate Math and Functional Programming) - recursion

I need to define a recursive ML function composition that accepts two relations and returns the composition of the two relations. I need to use the thhisIsTheImageOf and createRelationFromImage function in my definition of composition.
Here is the code that is needed to be used to define the composition
fun thisIsTheImageOf(e,[])=[]
|thisIsTheImageOf(e,(a,b)::xs) =
if e=a
then b::thisIsTheImageOf(e,xs)
else thisIsTheImageOf(e,xs);
Here are the datatype, value, and tested inputs for the thisIsTheImageOf function
datatype city =Vancouver|LosAngeles|Mexico|Minneapolis|Omaha |KansasCity|Denver|StLouis|Memphis|Chicago |NewOrleans|Cinncinati|Pittsburgh|Montreal|NewYork;
datatype rivers =Missouri|Platte|NPlatte|SPlatte|Arkansas|Canadian |Kansas|Mississippi|Tennessee|Ohio|Allegheny|Monongahela;
val isOnRiver=[(Denver,Platte),(Omaha,Missouri),(Omaha,Platte),(KansasCity,Missouri),(KansasCity,Kansas),(Minneapolis,Mississippi),(StLouis,Mississippi),(StLouis,Mi vssouri),(Memphis,Mississippi),(NewOrleans,Mississippi),(Cinncinati,Ohio),(Pittsburgh,Ohio),(Pittsburgh,Allegheny),(Pittsburgh,Monongahela)];
val flowsInto=[(Platte,Missouri),(Kansas,Missouri),(Missouri,Mississippi),(Allegheny,Ohio),(Monongahela,Ohio),(Tennessee,Ohio),(NPlatte,Platte),(SPlatte,Platte),(Ohio,Mississippi)];
thisIsTheImageOf(Pittsburgh, isOnRiver);thisIsTheImageOf(Mississippi, flowsInto);thisIsTheImageOf(Cinncinati, isOnRiver);
fun createRelationFromImage(e,[])=[]
createRelationFromImage(e,x::xs)= (e,x)::createRelationFromImage(e,xs);``
Here are tested inputs for the createRelationFromImage function
createRelationFromImage("Cincinnati",["New York", "Boston", "Dallas"]);
These two functions were created as a separate function but I am supposed to use the two functions to make a recursive function of composition.
I know the composition function mathematically and here is what I put as to help me see what I need to do
fun composition( i, r)x=i(r(x));
however, I am stuck on going further when trying to implement the two functions.

fun composition([],_ )=[]
| composition((a,b)::rest,relation)=
let
fun thisIsTheImageOf(e,[])=[]
|thisIsTheImageOf(e,(a,b)::xs) =
if e=a
then b::thisIsTheImageOf(e,xs)
else thisIsTheImageOf(e,xs);
fun createRelationFromImage(e,[])=[]
| createRelationFromImage(e,x::xs)= (e,x)::createRelationFromImage(e,xs);
in
createRelationFromImage(a, (thisIsTheImageOf(b, relation)))# composition(rest, relation)
end;

Related

How to achieve type stability when assigning values with StaticArrays?

I have the following struct (simplified), and some calculations done with this struct:
mutable struct XX{VecType}
v::VecType
end
long_calculation(x::XX) = sum(x.v)
as a part of the program i need to update the v value. the struct is callable and mainly used as a cache. here, the use of static arrays helps a lot in speeding up calculations, but the type of v is ultimately defined by an user. my problem lies when assigning new values to XX.v:
function (f::XX)(w)
f.v .= w #here lies the problem
return long_calculation(f)
this works if v <: Array and w is of any value, but it doesn't work when v <: StaticArrays.StaticArray, as setindex! is not defined on that type.
How can i write f.v .= w in a way that, when v allows it, performs an inplace modification, but when not, just creates a new value, and stores it in the XX struct?
There's a package for exactly this use case: BangBang.jl. From there, you can use setindex!!:
f.v = setindex!!(f.v, w)
Here I propose a simple solution that should be enough in most cases. Use multiple dispatch and define the following function:
my_assign!(f::XX, w) = (f.v .= w)
my_assign!(f::XX{<:StaticArray}, w) = (f.v = w)
and then simply call it in your code like this:
function (f::XX)(w)
my_assign!(f, w)
return long_calculation(f)
end
Then if you (or your users) get an error with a default implementation it is easy enough to add another method to my_assign! co cover other special cases when it throws an error.
Would such a solution be enough for you?

In functional programming, is there a clean way to perform many operations on some data without having to explicitly pass the data into each function?

Let's say that I have a few functions that perform business logic on some data:
function addEmployees(data, numberOfNewEmployees){
// Business logic...
data.employeeCount += numberOfNewEmployees;
return data;
}
function withdrawFunds(data, withdrawAmount){
// Business logic...
data.checkingAccount -= withdrawAmount;
return data;
}
function completeAnOrder(data){
// Business logic...
data.pendingOrders -- 1;
return data;
}
Now, to do several operations on some data, I have something like this (Let's assume that data is passed by copy):
const data = {
employeeCount: 5,
checkingAccount: 5000,
pendingOrders: 2
}
let newData = addEmployees(data, 2);
newData = withdrawFunds(newData, 2000);
newData = completeAnOrder(newData);
I was curious if there is an elegant method in the functional programming world to accomplish something closer to this:
const data = {
employeeCount: 5,
checkingAccount: 5000,
pendingOrders: 2
}
let biz = createBiz(data);
const newData = biz.addEmployees(2)
.withdrawFunds(2000)
.completeAnOrder()
.toValue();
In JavaScript I know that an object can return this and that is how JQuery method chaining works.
But is there a elegant method in the functional world to do something similar? I realize I may be trying to force an OOP idea into FP.
Is there a Monad that solves this problem? Does it make sense to create your own custom Monads for specific business logic?
This will heavily depend on the language and the tools the language has available.
In Clojure, which is homoiconic, tasks like this are often solved using macros. In this case, this would be accomplished using a "threading" macro.
Say I have your functions:
; All of these functions return the modified data
(defn add-employees [data number-of-new-employees]
...)
(defn withdraw-funds [data withdraw-amount]
...)
(defn complete-an-order [data]
...)
Since "this" (the data) is the first parameter, I can use -> to automatically "thread" the argument to each call:
(def data {:employee-count 5,
:checking-account 5000,
:pending-orders 2})
(-> data
(add-employees 2) ; The result of this gets passed as the first argument to withdraw-funds
(withdraw-funds 2000) ; Then the result of this gets passed to complete-an-order...
(complete-an-order) ; Same as above
(to-value))
After macro expansion, this basically gets turned into:
(to-value (complete-an-order (withdraw-funds (add-employees data 2) 2000)))
But it's much more readable and easier to change in the future using ->.
You would use composition. In Haskell, if the operations are pure functions that operate on a structure and return a new structure, and not I/O operations, you might write that several different ways, such as: toValue . completeOrder . withdrawFunds 2000 . addEmployees 2 $ data. (You can also write it left-to-right using &.)
You’re more likely to see that example turned into stateful code with side-effects on an external database, though. In Haskell, this would use the abstraction of applicatives or monads, but most other functional languages wouldn’t be such sticklers for mathematical formalism. The applicative version lets you write something like runValue $ completeOrder <$> withdrawFunds 2000 <$> addEmployees 2 <$> data. Or you can write this as do blocks.
Facebook gives some real-world examples of how it does this for some of its database code. The imperative code:
NumCommonFriends(x, y) = Length(Intersect(FriendsOf(x), FriendsOf(y)))
has the applicative version
numCommonFriends x y =
length <$> (intersect <$> friendsOf x <*> friendsOf y)
which can be written with some syntactic sugar as
numCommonFriends x y = do
fx <- friendsOf x
fy <- friendsOf y
return (length (intersect fx fy))

Julia: non-destructively update immutable type variable

Let's say there is a type
immutable Foo
x :: Int64
y :: Float64
end
and there is a variable foo = Foo(1,2.0). I want to construct a new variable bar using foo as a prototype with field y = 3.0 (or, alternatively non-destructively update foo producing a new Foo object). In ML languages (Haskell, OCaml, F#) and a few others (e.g. Clojure) there is an idiom that in pseudo-code would look like
bar = {foo with y = 3.0}
Is there something like this in Julia?
This is tricky. In Clojure this would work with a data structure, a dynamically typed immutable map, so we simply call the appropriate method to add/change a key. But when working with types we'll have to do some reflection to generate an appropriate new constructor for the type. Moreover, unlike Haskell or the various MLs, Julia isn't statically typed, so one does not simply look at an expression like {foo with y = 1} and work out what code should be generated to implement it.
Actually, we can build a Clojure-esque solution to this; since Julia provides enough reflection and dynamism that we can treat the type as a sort of immutable map. We can use fieldnames to get the list of "keys" in order (like [:x, :y]) and we can then use getfield(foo, :x) to get field values dynamically:
immutable Foo
x
y
z
end
x = Foo(1,2,3)
with_slow(x, p) =
typeof(x)(((f == p.first ? p.second : getfield(x, f)) for f in fieldnames(x))...)
with_slow(x, ps...) = reduce(with_slow, x, ps)
with_slow(x, :y => 4, :z => 6) == Foo(1,4,6)
However, there's a reason this is called with_slow. Because of the reflection it's going to be nowhere near as fast as a handwritten function like withy(foo::Foo, y) = Foo(foo.x, y, foo.z). If Foo is parametised (e.g. Foo{T} with y::T) then Julia will be able to infer that withy(foo, 1.) returns a Foo{Float64}, but won't be able to infer with_slow at all. As we know, this kills the crab performance.
The only way to make this as fast as ML and co is to generate code effectively equivalent to the handwritten version. As it happens, we can pull off that version as well!
# Fields
type Field{K} end
Base.convert{K}(::Type{Symbol}, ::Field{K}) = K
Base.convert(::Type{Field}, s::Symbol) = Field{s}()
macro f_str(s)
:(Field{$(Expr(:quote, symbol(s)))}())
end
typealias FieldPair{F<:Field, T} Pair{F, T}
# Immutable `with`
for nargs = 1:5
args = [symbol("p$i") for i = 1:nargs]
#eval with(x, $([:($p::FieldPair) for p = args]...), p::FieldPair) =
with(with(x, $(args...)), p)
end
#generated function with{F, T}(x, p::Pair{Field{F}, T})
:($(x.name.primary)($([name == F ? :(p.second) : :(x.$name)
for name in fieldnames(x)]...)))
end
The first section is a hack to produce a symbol-like object, f"foo", whose value is known within the type system. The generated function is like a macro that takes types as opposed to expressions; because it has access to Foo and the field names it can generate essentially the hand-optimised version of this code. You can also check that Julia is able to properly infer the output type, if you parametrise Foo:
#code_typed with(x, f"y" => 4., f"z" => "hello") # => ...::Foo{Int,Float64,String}
(The for nargs line is essentially a manually-unrolled reduce which enables this.)
Finally, lest I be accused of giving slightly crazy advice, I want to warn that this isn't all that idiomatic in Julia. While I can't give very specific advice without knowing your use case, it's generally best to have fields with a manageable (small) set of fields and a small set of functions which do the basic manipulation of those fields; you can build on those functions to create the final public API. If what you want is really an immutable dict, you're much better off just using a specialised data structure for that.
There is also setindex (without the ! at the end) implemented in the FixedSizeArrays.jl package, which does this in an efficient way.

In functional programming, can a function call another function that was declared outside of it's scope and not passed as a parameter?

Does using a function declared outside the scope of the function it is being used in violate a Functional principle like immutability? Or is that referring specifically to data like arrays, strings, etc.
For example:
var data ["cat", "dog", "bird"];
function doThing (val) {
return val + ", go away!"
}
function alterData (data) {
return data.map(doThing);
}
alterData(data);
Would the above code be acceptable? or would the "doThing" function need to be passed into the alterData function as an argument?
The reason I am confused is because in Functional Programming examples I often see functions native to the language being used without being first passed to the function. However, the examples are never complicated enough to show how one would work with a library of functions.
Regards
Functional programming is no different from procedural in that regard—you write definitions that you can reuse anywhere that they are in scope. You control what's in scope where with a variety of mechanisms, for example with module definitions, module export lists and module imports. So for example (in Haskell):
module My.Module
-- List of definitions exported from this module
( doThing
, alterData
) where
-- Any definitions exported from `My.Other.Module` will be in scope
-- in this one
import My.Other.Module
-- Can't name this `data` because it's a reserved word in Haskell
yourData :: [String]
yourData = ["cat", "dog", "bird"]
doThing :: String -> String
doThing val = val ++ ", go away!"
alterData :: [String] -> [String]
alterData strings = map doThings strings
TL;DR
It's fine to rely on scoping in FP code.
Immutability means that something represented by a name can't change its value. I wouldn't call it a "principle" of functional programming, though.
Anyway, this is not related to scoping at all. Passing things as arguments makes sense if you want to parametrize a function over another function - essentially making it a Higher-Order function. A good example of such is fold (also known as reduce) - but map is also one.
In your case alterData function isn't adding much value, though. mapping something over something is so common, that it's typically better to provide only the one-element function, as it's fundamentally more reusable.
If you've passed doThing to alterData, you'd make that function essentially useless; why would I use it, if I could simply use map? However, packing the operation together with the mapping can sometimes be an useful abstraction.
It is fine have doThing the way it is.
You need to do this :
var data = ["cat", "dog", "bird"];
var doThing = function (val) {
return val + ", go away!"
}
function alterData (data) {
return data.map(doThing);
}
alterData(data);

Is there a way of providing a final transform method when chaining operations (like map reduce) in underscore.js?

(Really strugging to title this question, so if anyone has suggestions feel free.)
Say I wanted to do an operation like:
take an array [1,2,3]
multiply each element by 2 (map): [2,4,6]
add the elements together (reduce): 12
multiply the result by 10: 120
I can do this pretty cleanly in underscore using chaining, like so:
arr = [1,2,3]
map = (el) -> 2*el
reduce = (s,n) -> s+n
out = (r) -> 10*r
reduced = _.chain(arr).map(map).reduce(reduce).value()
result = out(reduced)
However, it would be even nicer if I could chain the 'out' method too, like this:
result = _.chain(arr).map(map).reduce(reduce).out(out).value()
Now this would be a fairly simple addition to a library like underscore. But my questions are:
Does this 'out' method have a name in functional programming?
Does this already exist in underscore (tap comes close, but not quite).
This question got me quite hooked. Here are some of my thoughts.
It feels like using underscore.js in 'chain() mode' breaks away from functional programming paradigm. Basically, instead of calling functions on functions, you're calling methods of an instance of a wrapper object in an OOP way.
I am using underscore's chain() myself here and there, but this question made me think. What if it's better to simply create more meaningful functions that can then be called in a sequence without having to use chain() at all. Your example would then look something like this:
arr = [1,2,3]
double = (arr) -> _.map(arr, (el) -> 2 * el)
sum = (arr) -> _.reduce(arr, (s, n) -> s + n)
out = (r) -> 10 * r
result = out sum double arr
# probably a less ambiguous way to do it would be
result = out(sum(double arr))
Looking at real functional programming languages (as in .. much more functional than JavaScript), it seems you could do exactly the same thing there in an even simpler manner. Here is the same program written in Standard ML. Notice how calling map with only one argument returns another function. There is no need to wrap this map in another function like we did in JavaScript.
val arr = [1,2,3];
val double = map (fn x => 2*x);
val sum = foldl (fn (a,b) => a+b) 0;
val out = fn r => 10*r;
val result = out(sum(double arr))
Standard ML also lets you create operators which means we can make a little 'chain' operator that can be used to call those functions in a more intuitive order.
infix 1 |>;
fun x |> f = f x;
val result = arr |> double |> sum |> out
I also think that this underscore.js chaining has something similar to monads in functional programming, but I don't know much about those. Though, I have feeling that this kind of data manipulation pipeline is not something you would typically use monads for.
I hope someone with more functional programming experience can chip in and correct me if I'm wrong on any of the points above.
UPDATE
Getting slightly off topic, but one way to creating partial functions could be the following:
// extend underscore with partialr function
_.mixin({
partialr: function (fn, context) {
var args = Array.prototype.slice.call(arguments, 2);
return function () {
return fn.apply(context, Array.prototype.slice.call(arguments).concat(args));
};
}
});
This function can now be used to create a partial function from any underscore function, because most of them take the input data as the first argument. For example, the sum function can now be created like
var sum = _.partialr(_.reduce, this, function (s, n) { return s + n; });
sum([1,2,3]);
I still prefer arr |> double |> sum |> out over out(sum(double(arr))) though. Underscore's chain() is nice in that it reads in a more natural order.
In terms of the name you are looking for, I think what you are trying to do is just a form of function application: you have an underscore object and you want to apply a function to its value. In underscore, you can define it like this:
_.mixin({
app: function(v, f) { return f (v); }
});
then you can pretty much do what you asked for:
var arr = [1,2,3];
function m(el) { return 2*el; };
function r(s,n) { return s+n; };
function out(r) { return 10*r; };
console.log("result: " + _.chain(arr).map(m).reduce(r).app(out).value()));
Having said all that, I think using traditional typed functional languages like SML make this kind of think a lot slicker and give much lighter weight syntax for function composition. Underscore is doing a kind of jquery twist on functional programming that I'm not sure what I think of; but without static-type checking it is frustratingly easy to make errors!

Resources