How do I create Haskell functions that return functions? - function

I would like to create three Haskell functions: a, b, and c.
Each function is to have one argument. The argument is one of the three functions.
I would like function a to have this behavior:
if the argument is function a then return function a.
if the argument is function b then return function b.
if the argument is function c then return function a.
Here's a recap of the behavior I desire for function a:
a a = a
a b = c
a c = a
And here's the behavior I desire for the other two functions:
b a = a
b b = a
b c = c
c a = c
c b = b
c c = c
Once created, I would like to be able to compose the functions in various ways, for example:
a (c b)
= a (b)
= c
How do I create these functions?

Since you have given no criteria for how you are going to observe the results, then a = b = c = id satisfies your criteria. But of course that is not what you want. But the idea is important: it doesn't just matter what behavior you want your functions to have, but how you are going to observe that behavior.
There is a most general model if you allow some freedom in the notation, and you get this by using an algebraic data type:
data F = A | B | C
deriving (Eq, Show) -- ability to compare for equality and print
infixl 1 %
(%) :: F -> F -> F
A % A = A
A % B = C
A % C = A
B % A = A
...
and so on. Instead of saying a b, you have to say A % B, but that is the only difference. You can compose them:
A % (C % B)
= A % B
= B
and you can turn them into functions by partially applying (%):
a :: F -> F
a = (A %)
But you cannot compare this a, as ehird says. This model is equivalent to the one you specified, it just looks a little different.

This is impossible; you can't compare functions to each other, so there's no way to check if your argument is a, b, c or something else.
Indeed, it would be impossible for Haskell to let you check whether two functions are the same: since Haskell is referentially transparent, substituting two different implementations of the same function should have no effect. That is, as long as you give the same input for every output, the exact implementation of a function shouldn't matter, and although proving that \x -> x+x and \x -> x*2 are the same function is easy, it's undecidable in general.
Additionally, there's no possible type that a could have if it's to take itself as an argument (sure, id id types, but id can take anything as its first argument — which means it can't examine it in the way you want to).
If you're trying to achieve something with this (rather than just playing with it out of curiosity — which is fine, of course), then you'll have to do it some other way. It's difficult to say exactly what way that would be without concrete details.

Well, you can do it like this:
{-# LANGUAGE MagicHash #-}
import GHC.Prim
import Unsafe.Coerce
This function is from ehird's answer here:
equal :: a -> a -> Bool
equal x y = x `seq` y `seq`
case reallyUnsafePtrEquality# x y of
1# -> True
_ -> False
Now, let's get to business. Notice that you need to coerce the arguments and the return values as there is no possible type these functions can really have, as ehird pointed out.
a,b,c :: x -> y
a x | unsafeCoerce x `equal` a = unsafeCoerce a
| unsafeCoerce x `equal` b = unsafeCoerce c
| unsafeCoerce x `equal` c = unsafeCoerce a
b x | unsafeCoerce x `equal` a = unsafeCoerce a
| unsafeCoerce x `equal` b = unsafeCoerce a
| unsafeCoerce x `equal` c = unsafeCoerce c
c x | unsafeCoerce x `equal` a = unsafeCoerce c
| unsafeCoerce x `equal` b = unsafeCoerce b
| unsafeCoerce x `equal` c = unsafeCoerce c
Finally, some tests:
test = a (c b) `equal` c -- Evaluates to True
test' = a (c b) `equal` a -- Evaluates to False
Ehh...

As noted, functions can't be compared for equality. If you simply want functions that satisfy the algebraic laws in your specificiation, making them all equal to the identity function will do nicely.
I hope you are aware that if you post a homework-related question to Stack Overflow, the community expects you to identify it as such.

Related

What are the logical and arithmetical functions from the 74LS181

i want to use the 74ls181 in an Project of mine but i can not understand all of the functions of it mentioned in its datasheet.
Could someone please explain this boolean-mess?
EDIT:
Based on the very helpful answer from Axel Kemper i created this:
Your table was taken from the Texas Instruments 74ls181 datasheet?
Assuming from your question tags that you are asking about the logical functions
(explained from top to bottom as in the table):
F = NOT(A) set output to inverse of all A bits
F = NAND(A, B) inverse AND of inputs
F = OR(NOT(A), B)
F = 1 set all output bits to 1
F = NOR(A, B)
F = NOT(B) feed inverse B bits to output
F = NOT(EXOR(A, B))
F = OR(A, NOT(B))
F = AND(NOT(A), B)
F = EXOR(A, B) output is exclusive or of inputs
F = B feed B inputs bits to outputs
F = OR(A, B) bitwise disjunction
F = 0 set all output bits to 0
F = AND(A, NOT(B))
F = AND(A, B) bitwise conjuction
F = A
All functions are implemented 4-bit parallel.
A, B and F each have four signal lines.
A and B are the four-bit inputs. F is the four-bit output.
So, A=0 for example means A0=0, A1=0, A2=0, A3=0
There is a total of 16 different logical functions possible to implement with two inputs and one output. 74ls181 implements all of them.
A truth-table with two inputs and one output has four rows.
Each of the rows has output value 0 or 1. Therefore, a four-bit number defines the function described by the truth-table.
With four bits, 16 functions are possible.
There is a very instructive YouTube video available on the 74ls181.

How to find maximum of function outputs with multipe inputs in one function?

I want a function maxfunct, with input f (a function) and input n (int), that computes all outputs of function f with inputs 0 to n, and checks for the max value of the output.
I am quite new to haskell, what I tried is something like that:
maxfunct f n
| n < 0 = 0
| otherwise = maximum [k | k <- [\(f, x)-> f x], x<- [0..n]]
Idea is that I store every output of f in a list, and check for the maximum in this list.
How can I achieve that?
You're close. First, let's note the type of the function we're trying to write. Starting with the type, in addition to helping you get a better feel for the function, also lets the compiler give us better error messages. It looks like you're expecting a function and an integer. The result of the function should be compatible with maximum (i.e. should satisfy Ord) and also needs to have a reasonable "zero" value (so we'll just say it needs Num, for simplicity's sake; in reality, we might consider using Bounded or Monoid or something, depending on your needs, but Num will suffice for now).
So here's what I propose as the type signature.
maxfunct :: (Num a, Ord a) => (Int -> a) -> Int -> a
Technically, we could generalize a bit more and make the Int a type argument as well (requires Num, Enum, and Ord), but that's probably overkill. Now, let's look at your implementation.
maxfunct f n
| n < 0 = 0
| otherwise = maximum [k | k <- [\(f, x)-> f x], x<- [0..n]]
Not bad. The first case is definitely good. But I think you may have gotten a bit confused in the list comprehension syntax. What we want to say is: take every value from 0 to n, apply f to it, and then maximize.
maxfunct :: (Num a, Ord a) => (Int -> a) -> Int -> a
maxfunct f n
| n < 0 = 0
| otherwise = maximum [f x | x <- [0..n]]
and there you have it. For what it's worth, you can also do this with map pretty easily.
maxfunct :: (Num a, Ord a) => (Int -> a) -> Int -> a
maxfunct f n
| n < 0 = 0
| otherwise = maximum $ map f [0..n]
It's just a matter of which you find more easily readable. I'm a map / filter guy myself, but lots of folks prefer list comprehensions, so to each his own.

Finding inverse functions [duplicate]

In pure functional languages like Haskell, is there an algorithm to get the inverse of a function, (edit) when it is bijective? And is there a specific way to program your function so it is?
In some cases, yes! There's a beautiful paper called Bidirectionalization for Free! which discusses a few cases -- when your function is sufficiently polymorphic -- where it is possible, completely automatically to derive an inverse function. (It also discusses what makes the problem hard when the functions are not polymorphic.)
What you get out in the case your function is invertible is the inverse (with a spurious input); in other cases, you get a function which tries to "merge" an old input value and a new output value.
No, it's not possible in general.
Proof: consider bijective functions of type
type F = [Bit] -> [Bit]
with
data Bit = B0 | B1
Assume we have an inverter inv :: F -> F such that inv f . f ≡ id. Say we have tested it for the function f = id, by confirming that
inv f (repeat B0) -> (B0 : ls)
Since this first B0 in the output must have come after some finite time, we have an upper bound n on both the depth to which inv had actually evaluated our test input to obtain this result, as well as the number of times it can have called f. Define now a family of functions
g j (B1 : B0 : ... (n+j times) ... B0 : ls)
= B0 : ... (n+j times) ... B0 : B1 : ls
g j (B0 : ... (n+j times) ... B0 : B1 : ls)
= B1 : B0 : ... (n+j times) ... B0 : ls
g j l = l
Clearly, for all 0<j≤n, g j is a bijection, in fact self-inverse. So we should be able to confirm
inv (g j) (replicate (n+j) B0 ++ B1 : repeat B0) -> (B1 : ls)
but to fulfill this, inv (g j) would have needed to either
evaluate g j (B1 : repeat B0) to a depth of n+j > n
evaluate head $ g j l for at least n different lists matching replicate (n+j) B0 ++ B1 : ls
Up to that point, at least one of the g j is indistinguishable from f, and since inv f hadn't done either of these evaluations, inv could not possibly have told it apart – short of doing some runtime-measurements on its own, which is only possible in the IO Monad.
                                                                                                                                   ⬜
You can look it up on wikipedia, it's called Reversible Computing.
In general you can't do it though and none of the functional languages have that option. For example:
f :: a -> Int
f _ = 1
This function does not have an inverse.
Not in most functional languages, but in logic programming or relational programming, most functions you define are in fact not functions but "relations", and these can be used in both directions. See for example prolog or kanren.
Tasks like this are almost always undecidable. You can have a solution for some specific functions, but not in general.
Here, you cannot even recognize which functions have an inverse. Quoting Barendregt, H. P. The Lambda Calculus: Its Syntax and Semantics. North Holland, Amsterdam (1984):
A set of lambda-terms is nontrivial if it is neither the empty nor the full set. If A and B are two nontrivial, disjoint sets of lambda-terms closed under (beta) equality, then A and B are recursively inseparable.
Let's take A to be the set of lambda terms that represent invertible functions and B the rest. Both are non-empty and closed under beta equality. So it's not possible to decide whether a function is invertible or not.
(This applies to the untyped lambda calculus. TBH I don't know if the argument can be directly adapted to a typed lambda calculus when we know the type of a function that we want to invert. But I'm pretty sure it will be similar.)
If you can enumerate the domain of the function and can compare elements of the range for equality, you can - in a rather straightforward way. By enumerate I mean having a list of all the elements available. I'll stick to Haskell, since I don't know Ocaml (or even how to capitalise it properly ;-)
What you want to do is run through the elements of the domain and see if they're equal to the element of the range you're trying to invert, and take the first one that works:
inv :: Eq b => [a] -> (a -> b) -> (b -> a)
inv domain f b = head [ a | a <- domain, f a == b ]
Since you've stated that f is a bijection, there's bound to be one and only one such element. The trick, of course, is to ensure that your enumeration of the domain actually reaches all the elements in a finite time. If you're trying to invert a bijection from Integer to Integer, using [0,1 ..] ++ [-1,-2 ..] won't work as you'll never get to the negative numbers. Concretely, inv ([0,1 ..] ++ [-1,-2 ..]) (+1) (-3) will never yield a value.
However, 0 : concatMap (\x -> [x,-x]) [1..] will work, as this runs through the integers in the following order [0,1,-1,2,-2,3,-3, and so on]. Indeed inv (0 : concatMap (\x -> [x,-x]) [1..]) (+1) (-3) promptly returns -4!
The Control.Monad.Omega package can help you run through lists of tuples etcetera in a good way; I'm sure there's more packages like that - but I don't know them.
Of course, this approach is rather low-brow and brute-force, not to mention ugly and inefficient! So I'll end with a few remarks on the last part of your question, on how to 'write' bijections. The type system of Haskell isn't up to proving that a function is a bijection - you really want something like Agda for that - but it is willing to trust you.
(Warning: untested code follows)
So can you define a datatype of Bijection s between types a and b:
data Bi a b = Bi {
apply :: a -> b,
invert :: b -> a
}
along with as many constants (where you can say 'I know they're bijections!') as you like, such as:
notBi :: Bi Bool Bool
notBi = Bi not not
add1Bi :: Bi Integer Integer
add1Bi = Bi (+1) (subtract 1)
and a couple of smart combinators, such as:
idBi :: Bi a a
idBi = Bi id id
invertBi :: Bi a b -> Bi b a
invertBi (Bi a i) = (Bi i a)
composeBi :: Bi a b -> Bi b c -> Bi a c
composeBi (Bi a1 i1) (Bi a2 i2) = Bi (a2 . a1) (i1 . i2)
mapBi :: Bi a b -> Bi [a] [b]
mapBi (Bi a i) = Bi (map a) (map i)
bruteForceBi :: Eq b => [a] -> (a -> b) -> Bi a b
bruteForceBi domain f = Bi f (inv domain f)
I think you could then do invert (mapBi add1Bi) [1,5,6] and get [0,4,5]. If you pick your combinators in a smart way, I think the number of times you'll have to write a Bi constant by hand could be quite limited.
After all, if you know a function is a bijection, you'll hopefully have a proof-sketch of that fact in your head, which the Curry-Howard isomorphism should be able to turn into a program :-)
I've recently been dealing with issues like this, and no, I'd say that (a) it's not difficult in many case, but (b) it's not efficient at all.
Basically, suppose you have f :: a -> b, and that f is indeed a bjiection. You can compute the inverse f' :: b -> a in a really dumb way:
import Data.List
-- | Class for types whose values are recursively enumerable.
class Enumerable a where
-- | Produce the list of all values of type #a#.
enumerate :: [a]
-- | Note, this is only guaranteed to terminate if #f# is a bijection!
invert :: (Enumerable a, Eq b) => (a -> b) -> b -> Maybe a
invert f b = find (\a -> f a == b) enumerate
If f is a bijection and enumerate truly produces all values of a, then you will eventually hit an a such that f a == b.
Types that have a Bounded and an Enum instance can be trivially made RecursivelyEnumerable. Pairs of Enumerable types can also be made Enumerable:
instance (Enumerable a, Enumerable b) => Enumerable (a, b) where
enumerate = crossWith (,) enumerate enumerate
crossWith :: (a -> b -> c) -> [a] -> [b] -> [c]
crossWith f _ [] = []
crossWith f [] _ = []
crossWith f (x0:xs) (y0:ys) =
f x0 y0 : interleave (map (f x0) ys)
(interleave (map (flip f y0) xs)
(crossWith f xs ys))
interleave :: [a] -> [a] -> [a]
interleave xs [] = xs
interleave [] ys = []
interleave (x:xs) ys = x : interleave ys xs
Same goes for disjunctions of Enumerable types:
instance (Enumerable a, Enumerable b) => Enumerable (Either a b) where
enumerate = enumerateEither enumerate enumerate
enumerateEither :: [a] -> [b] -> [Either a b]
enumerateEither [] ys = map Right ys
enumerateEither xs [] = map Left xs
enumerateEither (x:xs) (y:ys) = Left x : Right y : enumerateEither xs ys
The fact that we can do this both for (,) and Either probably means that we can do it for any algebraic data type.
Not every function has an inverse. If you limit the discussion to one-to-one functions, the ability to invert an arbitrary function grants the ability to crack any cryptosystem. We kind of have to hope this isn't feasible, even in theory!
In some cases, it is possible to find the inverse of a bijective function by converting it into a symbolic representation. Based on this example, I wrote this Haskell program to find inverses of some simple polynomial functions:
bijective_function x = x*2+1
main = do
print $ bijective_function 3
print $ inverse_function bijective_function (bijective_function 3)
data Expr = X | Const Double |
Plus Expr Expr | Subtract Expr Expr | Mult Expr Expr | Div Expr Expr |
Negate Expr | Inverse Expr |
Exp Expr | Log Expr | Sin Expr | Atanh Expr | Sinh Expr | Acosh Expr | Cosh Expr | Tan Expr | Cos Expr |Asinh Expr|Atan Expr|Acos Expr|Asin Expr|Abs Expr|Signum Expr|Integer
deriving (Show, Eq)
instance Num Expr where
(+) = Plus
(-) = Subtract
(*) = Mult
abs = Abs
signum = Signum
negate = Negate
fromInteger a = Const $ fromIntegral a
instance Fractional Expr where
recip = Inverse
fromRational a = Const $ realToFrac a
(/) = Div
instance Floating Expr where
pi = Const pi
exp = Exp
log = Log
sin = Sin
atanh = Atanh
sinh = Sinh
cosh = Cosh
acosh = Acosh
cos = Cos
tan = Tan
asin = Asin
acos = Acos
atan = Atan
asinh = Asinh
fromFunction f = f X
toFunction :: Expr -> (Double -> Double)
toFunction X = \x -> x
toFunction (Negate a) = \a -> (negate a)
toFunction (Const a) = const a
toFunction (Plus a b) = \x -> (toFunction a x) + (toFunction b x)
toFunction (Subtract a b) = \x -> (toFunction a x) - (toFunction b x)
toFunction (Mult a b) = \x -> (toFunction a x) * (toFunction b x)
toFunction (Div a b) = \x -> (toFunction a x) / (toFunction b x)
with_function func x = toFunction $ func $ fromFunction x
simplify X = X
simplify (Div (Const a) (Const b)) = Const (a/b)
simplify (Mult (Const a) (Const b)) | a == 0 || b == 0 = 0 | otherwise = Const (a*b)
simplify (Negate (Negate a)) = simplify a
simplify (Subtract a b) = simplify ( Plus (simplify a) (Negate (simplify b)) )
simplify (Div a b) | a == b = Const 1.0 | otherwise = simplify (Div (simplify a) (simplify b))
simplify (Mult a b) = simplify (Mult (simplify a) (simplify b))
simplify (Const a) = Const a
simplify (Plus (Const a) (Const b)) = Const (a+b)
simplify (Plus a (Const b)) = simplify (Plus (Const b) (simplify a))
simplify (Plus (Mult (Const a) X) (Mult (Const b) X)) = (simplify (Mult (Const (a+b)) X))
simplify (Plus (Const a) b) = simplify (Plus (simplify b) (Const a))
simplify (Plus X a) = simplify (Plus (Mult 1 X) (simplify a))
simplify (Plus a X) = simplify (Plus (Mult 1 X) (simplify a))
simplify (Plus a b) = (simplify (Plus (simplify a) (simplify b)))
simplify a = a
inverse X = X
inverse (Const a) = simplify (Const a)
inverse (Mult (Const a) (Const b)) = Const (a * b)
inverse (Mult (Const a) X) = (Div X (Const a))
inverse (Plus X (Const a)) = (Subtract X (Const a))
inverse (Negate x) = Negate (inverse x)
inverse a = inverse (simplify a)
inverse_function x = with_function inverse x
This example only works with arithmetic expressions, but it could probably be generalized to work with lists as well. There are also several implementations of computer algebra systems in Haskell that may be used to find the inverse of a bijective function.
No, not all functions even have inverses. For instance, what would the inverse of this function be?
f x = 1

Explanation of a Haskell function from an old exam

I'm reviewing an old exam in my Haskell programming course and I can't seem to wrap my head around this function (I think there is just too little information given).
The code given is
myId x = x
function n f
| n > 0 = f . function (n-1) f
| otherwise = myId
I know that if I for example call the function with the input 2 (*2), I will get a function as result. And if I call it with (-2) (*2) 1 I will get the result 1.
I just don't know how? Also I can't wrap my head around the typecast of the function.
I know that these two options are correct but I don't understand why (probably parentheses that confuse me at the moment).
function :: (Num a, Ord a) => a -> (a -> a) -> a -> a
function :: (Num a, Ord b) => a -> (b -> b) -> b -> b
Anyone that can clarify how I should "read" this function and how I should understand how the typecast works (been reading my Programming in Haskell literature and from Learn You a Haskell but been going in circle for a few days now).
function takes some number n and a function f :: a -> a, and composes that function with itself n times, returning another function of type a -> a. When the returned function is applied to a value of type a, the result is essentially the same as executing f in a loop n times, using the output of each previous step as the input for the next.
Perhaps it is easier to see the similarity if the final parameter is made explicit:
function :: (Ord a, Num a) -> a -> (b -> b) -> b -> b
function n f x
| n > 0 = f (function (n-1) f x)
| otherwise = x
This is functionally equivalent to your point-free function.
In Haskell, a function f :: a -> b -> c can be interpreted either as "a function that takes an a and a b and returns a c" or "a function that takes an a and returns a function from b to c". When you apply a function to one or more inputs, think of each input as eliminating one of the function's arguments. In this instance, function 10 returns a new function with type (a -> a) -> a -> a, and function 2 (*2) returns a function with type Num a => a -> a.
When you think of it this way, it should hopefully be clear why function (-2) (*2) 1 returns a number while function 2 (*2) returns a function. There is no type casting going on; when you are applying the three argument function to two inputs, you get another function back instead of a value, since you didn't provide the final input needed to compute that value.

What are those functional functions called?

I'm looking for a functional way to implement this:
list = [a b c d e f]
foo(list, 3) = [[a d] [b e] [c f]]
A potential solution is:
foo(list,spacing) = zip(goo(list,spacing))
Where, for example,
goo([a b c d e f],3) = [[a b c] [d e f]]
What is foo and goo usually called, so I can look for existing solutions rather than reinventing the wheel?
Notes: Rather than trying to explain with words, I've just shown examples that'll be hopefully much easier to get. Arbitrary syntax for broader understanding.
You can use partition:
(partition 3 '[a b c d e f])
=> ((a b c) (d e f))
(partition 2 '[a b c d e f])
=> ((a b) (c d) (e f))
Edit:
(apply map list (partition 3 '[a b c d e f]))
=> ((a d) (b e) (c f))
I do not think there is a built-in function for that. It's easy and nice to implement.
I know you do not want the implementation, but one of the tags was Haskell so maybe you want to see this
p :: Int -> [a] -> [[a]]
p n xs = [ [x | (x ,y) <- ys , y `mod` n == i] | i <- [0 .. n - 1] , let ys = zip xs [0 .. ]]
That is pretty functional.
Your goo function is drop with flipped arguments. Given that, you can implement foo almost like you say in your question:
let foo list spacing = zip list (drop spacing list)
This still doesn't exactly give the result you need though, but close:
Prelude> foo "abcdef" 3
[('a','d'),('b','e'),('c','f')]
EDIT:
Reading more carefully, your goo function is splitAt with flipped arguments. Given that, foo can be defined like this:
let foo list spacing = (uncurry zip) $ splitAt spacing list
Which is the same as:
let foo list spacing = let (left, right) = splitAt spacing list
in zip left right