This works in the ghci
data MyList a = Empty | Cons a (MyList a) deriving (Show, Eq, Read, Ord)
let x = Cons(21, Cons(12, Empty))
However when I type:
Prelude> x
I get this error:
No instance for (Show (MyList (Integer, MyList (Integer, MyList a0) ->
MyList (Integer, MyList a0)) ->
MyList (Integer, MyList (Integer, MyList a0) ->
MyList (Integer, MyList a0)))) arising from a use of `print'
You are using the wrong syntax for function application. The following code does what you want:
let x = Cons 21 (Cons 12 Empty)
The reason for this is that the Cons constructor is a curried function, but you are treating it as an uncurried function.
Curried functions
Consider the following function adding two integers:
add :: Int -> (Int -> Int)
add = \x -> (\y -> x + y)
Here we say add is a function, which takes an argument x of type Int and returns a function,
which takes an argument y of type Int and returns x + y of type Int.
We can apply this function for example as (add 1) 2 evaluating to 3.
Function application is left-associative in Haskell, which means that we don't need the parentheses
in (add 1) 2 and can simply write add 1 2.
The function type constructor -> is right-associative in Haskell, which means that we don't need the parentheses in add :: Int -> (Int -> Int) and can simply write add :: Int -> Int -> Int.
Also we don't have to explicitly define add using lambdas and can use the following notation:
add :: Int -> Int -> Int
add x y = x + y
Encoding multi-parameter functions as single-parameter functions returning single-parameter functions is quite common in Haskell. This approach has the nice property, that we can also partially apply a function. For example the following function takes a single Int and adds 2:
add2 :: Int -> Int
add2 x = add 2 x
But we can also partially apply add and simply write:
add2 :: Int -> Int
add2 = add 2
This is also called point-free notation, where parameters are referred to as points.
Uncurried functions
An alternative encoding of multi-parameter functions can be done using tuple-values, i.e.
add' :: (Int, Int) -> Int
add' (x, y) = x + y
We can invoke this function for example as add' (2, 3), which constructs the pair (2, 3) :: (Int, Int) and passes it as a single argument to the add' function.
Uncurried <-> Curried
In the standard library are two functions to convert functions between the two styles.
curry :: ((a, b) -> c) -> a -> b -> c
curry f x y = f (x, y)
uncurry :: (a -> b -> c) -> (a, b) -> c
uncurry f (x, y) = f x y
For example curry add' gives us add, and uncurry add gives us add'.
Back to explaining ghci's rambling
Note that we could also write the uncurried application as add'(2, 3), which together with partial application and polymorphism explains why let x = Cons(21, Cons(12, Empty)) doesn't directly lead to an error, but ghci subsequently says misterious things about the evaluation of x.
What happens here is that (12, Empty) is pair of type (Int, MyList a) for some type a.
This pair is then used as the first argument in Cons (12, Empty), so we get a partially applied function which takes
a MyList (Int, MyList a) and appends (12, Empty) as an element to this list.
The same happens for Cons(21, Cons(12, Empty)) where we partially apply a pair of 21 and the before mentioned partial function. In the end we tell ghci to print a function, which it cannot display and hence complains about a missing Show instance for the corresponding function type.
Related
I've created a list of partially applied functions in my REPL like so:
listOfPartiallyAppliedFunctions = map (*) [1..100]
I would then like to create the list of results from completing the function application, which I can easily do by providing a lambda to the map function like so:
let results = map (\x -> x 4) listOfPartiallyAppliedFunctions
Which basically means map the function x applied to 4 over the list of partially applied functions, where x is each partially applied function from the list.
However, I thought it would then follow that I could write:
let results = map (4) listOfPartiallyAppliedFunctions
As there shouldn't be a need to provide a lambda to the map function as it should know to apply 4 to the partially applied functions contained in the listOfPartiallyAppliedFunctions.
However, I am getting this error:
• Non type-variable argument in the constraint: Num ((a -> a) -> b)
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall a b. (Num a, Num ((a -> a) -> b), Enum a) => [b]
Can someone help me parse this error? I thought 4 was an instance of type constructor Num?
However, I thought it would then follow that I could write:
let results = map (4) listOfPartiallyAppliedFunctions
No, if you would have performed \x -> 4 x, you could replace it with 4. But since 4 means it is a Num instance, and you likely did not make a function a -> b an instance of Num, the compiler can not solve this. The compiler thus says that it does not find a way to convert the number 4 into a function, and definitely not a function that takes as input a function Num a => a -> a, and then converts this to a b.
You can however write the above as just:
let results = map ($ 4) listOfPartiallyAppliedFunctions
Here we thus perform a sectioning of an infix operator [Haskell-wiki] on the ($) :: (a -> b) -> a -> b function.
Three "laws" of operator sections are
(a `op` b) = (a `op`) b = (`op` b) a = op a b
(the missing argument goes into the free slot near the operator),
or with $,
a b = (a $ b) = (a $) b = ($ b) a = ($) a b
Thus
(\ x -> x 4) = (\ x -> x $ 4) = (\ x -> ($ 4) x)
and that, by eta-reduction, is
($ 4)
From https://stackoverflow.com/a/57020455/156458
In Haskell, it happens that everything is curried; all functions take just one argument (even uncurried functions in Haskell take a tuple, which is, strictly speaking, a single argument -- you might want to play with the curry and uncurry functions to see how that works).
I am not sure if that is true, but assume so.
If a function takes another function as an argument, is it curried or uncurried in a similar sense as a function taking a tuple or list argument being uncurried? (A pair tuple type is type1 x type2 and can be type1^2, while a function type is type2^{type1}, so I find them similar)
If uncurried, how can I convert such a function to a curried function?
If a function takes another function as an argument, is it curried or uncurried?
It takes just a function, so a single parameter, and hence it is curried. The fact that that parameter is a function is irrelevant.
Such a function is for example map. map has type:
map :: (a -> b) -> ([a] -> [b])
It thus takes a single parameter, a function (of type a -> b), and then returns a function [a] -> [b] that will map a list of as to a list of bs by applying that function.
So map show :: Show a => [a] -> [String] is the result of such function application, and this is again a function.
Yes, the quote is correct. All the talk about "curried" and "uncurried" functions is imprecise jargon.
Haskell is a curried language. Functions in Haskell always have exponential types. If an argument is a tuple, it doesn't matter, it is still just one value (which happens to be a tuple).
The concepts are approximated when we treat an (a,b) -> c Haskell function as the c a * b one. But it's just a mental gymnastics that we do.
What's actually curried or not, are programming languages. For instance, in Lisp,
(lambda (a b) c)
actually has the type c a * b and to turn it into the (c b)a function we need to put it through some transformations.
There actually is no (\a b -> c) lambdas in Haskell, only (\ a -> (\ b -> c)) nested lambdas(*) . When we write (\a b -> c) in Haskell, it is just a syntactical shortcut for (\ a -> (\ b -> c)). It is impossible to have actual (\a b -> c) lambda function in Haskell, though it is approximated by having (\(a,b) -> c) lambda function.
Where you really see the meaning of all this, if when you implement your own language with lambda functions.
Faced with a ((lambda (a b) c) x y z) function call, the real issue is how to pair-up the function's parameters and the values supplied.
Haskell converts it into ((let a=x in (let b=y in c)) z), but Lisp actually pairs up the parameters list (a b) with the list of values (x y z) and reports the length mismatch.
But, being the uncurried language that it is, Lisp is able to have the various twists and tweaks here, like optional arguments, default arguments, named arguments, etc., pairing up the parameters and the values in various different ways -- unlike Haskell, which always pairs up one parameter with one supplied value at a time.
(*) and with another crucial distinction: the a and b in Haskell's (\ a -> (\ b -> c)) are not variables, but patterns. They are not just assigned the values, like in Lisp -- they are matched up with them.
The truth I can see at least, is almost every value in haskell can be seen as a function with, and every function just take one parameter at the time. Let see an example (With Int as example, to be more clear):
f :: Int -> Int -> Int -> Int
f x y z = x + y + z
f can be seen as a function that takes a Int and returns a function
Int -> (Int -> Int)
:t (f 2)
(f 2) :: Int -> Int -> Int
:t (f 2 3)
(f 2 3) :: Int -> Int
(f 2 3) can be seen as a function that takes a Int and returns an Int
finally
:t (f 2 3 4)
(f 2 3 4) :: Int
An example with higher order functions:
h :: (Int -> Int -> Int) -> Int -> Int -> Int
h fn x y = fn x y
A little more complex but just the same idea:
:t (h f)
(h f) :: Int -> Int -> Int -> Int
(h f) is a function, expecting an Int , and returning (Int -> Int -> Int -> Int)
but... wait, was not it expecting to return a function? it should be so
(h f) :: Int -> Int -> (Int -> Int)
well, point made. let's continue
:t (h f 2)
(h f 2) :: Int -> Int -> Int
(h f 2) is a function expecting a Int and returning a function (Int -> Int)
and finally
:t (h f 2 3)
(h f 2 3) :: Int -> Int
(h f 2 3) indeed is a function, expecting a Int, returning an Int
(h f 2 3) 4 == 7
I think the conclusion here is, every function is curried in Haskell.
I was trying to write a QuickCheck test for the identity
f $ y = f y
My initial plan was to write an arbitrary generator that returns functions & Integer, having the signature Gen (Int -> Int, Int)
and in the prop_DollerDoesNothing test that function application with / without the $ gives the same result.
This was my code:
prop_DollarDoesNothing :: Property
prop_DollarDoesNothing =
forAll arbitraryFuncInt (\(f, y) -> (f $ y) == (f y))
arbitraryFuncInt :: Gen (Int -> Int, Int)
arbitraryFuncInt = do
f <- elements [(\x -> x*2), (\x -> x+3), (\x -> x-2)]
y <- arbitrary :: Gen Int
return (f, y)
And it generated the following helpful error message:
* No instance for (Show (Int -> Int))
arising from a use of `forAll'
(maybe you haven't applied a function to enough arguments?)
* In the expression:
forAll arbitraryFuncInt (\ (f, y) -> (f $ y) == (f y))
In an equation for `prop_DollarDoesNothing':
prop_DollarDoesNothing
= forAll arbitraryFuncInt (\ (f, y) -> (f $ y) == (f y))
So, I fixed the error and got the test working by applying the arbitrary function and returning a pair of ints from arbitraryFuncInt
prop_DollarDoesNothing :: Property
prop_DollarDoesNothing =
forAll arbitraryFuncInt (\(x, y) -> x == y)
arbitraryFuncInt :: Gen (Int, Int)
arbitraryFuncInt = do
f <- elements [(\x -> x*2), (\x -> x+3), (\x -> x-2)]
y <- arbitrary :: Gen Int
return (f $ y, f y)
My questions are:
is it simply not possible to return arbitrary functions that aren't fully applied due to not having an instance for Show?
Can I write an instance for Show (Int -> Int) to make # 1 possible?
Can QuickCheck generate arbitrary functions given a type signature, for cases where I'm testing identities that are true for all functions (of a given type). Above, I specify the 3 test functions by hand, I'd like to automate that somehow, ideally something like this f <- arbitrary :: Gen (Int -> Int)
QuickCheck has support to generate, shrink and show functions, using the Fun type. CoArbitrary enables generation of functions. It is then converted to a (possibly infinite) trie-like structure, that can be inspected and shrunk to a finite value (because a test failure only depends on finitely many inputs), which can then be shown as a counterexample.
Concretely, you can write properties as function that take a Fun argument, which is a wrapper around (->) using the mechanism I described. Deconstruct it with the Fn pattern to get a function.
prop_dollarDoesNothing :: Property
prop_dollarDoesNothing = property $ \(Fn (f :: Int -> Int)) x ->
(f $ x) === f x
For more information
The QuickCheck implementation: https://hackage.haskell.org/package/QuickCheck-2.11.3/docs/Test-QuickCheck-Function.html
The paper "Shrinking and showing functions" by Koen Claessen, which appears to be paywalled, but his talk is online: https://www.youtube.com/watch?v=CH8UQJiv9Q4
Arbitrary can generate functions just fine (provided the arguments are instances of CoArbitrary), it's just the showing part that doesn't work. There's not really a good way to show a function.
This is a common problem, and therefore QuickCheck provides the Blind modifier. It basically fakes a Show instances for any type, not actually showing any information about the value. Of course this somewhat diminishes the debugging-usefulness of a failing test case, but there's not much that can done about this.
I'm trying to generate a truth table for a given boolean expression. I could do this with creating a new Datatype BoolExpr, but I want to do it with an anonymous function. It's supposed to work like this:
> tTable (\x y -> not (x || y))
output:
F F | T
F T | F
T F | F
T T | F
My approach:
tbl p = [(uncurry p) tuple | tuple <- allval]
where allval=[(x,y) | x <- [False,True], y <- [False,True]]
This works, but only for 2 Arguments. I want to do it for any number of Arguments. So I figured I would make a function that takes the Arguments from a List:
argsFromList f [] = f
argsFromList f (x:xs) = argsFromList (f x) xs
This does not work:
Occurs check: cannot construct the infinite type: t = t1 -> t
Expected type: t -> [t1] -> t1 -> t
Inferred type: (t1 -> t) -> [t1] -> t1 -> t
In the expression: argsFromList (f x) xs
I don't understand what the problem is here.
I would be very grateful if anyone could point me into the right direction or post a link that does.
If you want to build a truth table for boolean functions with an arbitrary number of arguments, you're creating a function that must work for multiple types, so you'll have to use type classes:
{-# LANGUAGE FlexibleInstances #-}
class TruthTable a where
truthTable :: a -> [([Bool], Bool)]
instance TruthTable Bool where
truthTable b = [([], b)]
instance TruthTable a => TruthTable (Bool -> a) where
truthTable f = [ (True : inps, out) | (inps, out) <- truthTable (f True)] ++
[ (False : inps, out) | (inps, out) <- truthTable (f False)]
For example:
*Main> mapM_ print $ truthTable (&&)
([True,True],True)
([True,False],False)
([False,True],False)
([False,False],False)
The problem here is that you're trying to call a function recursively with a different type for the recursive step. Consider the definition:
argsFromList f [] = f
argsFromList f (x:xs) = argsFromList (f x) xs
Let's try to infer the type ourselves. We can immediately see that the first argument f should be a function of at least one argument, the second argument (x:xs) is a list, and the list elements should be the same type as the first argument of f. In the first case the argument f is returned, so the final return type must be the same as the first argument. So we start with this:
argsFromList :: (a -> ?) -> [a] -> (a -> ?)
To find the unknown type ?, we can look at the second case, which consists of a recursive call. The argument xs is the same list type, and the argument (f x) has type ?. Since it's being used as the first argument in the recursive call, which has type (a -> ?), we can now conclude that ? is the same type as (a -> ?) which is therefore the same type as (a -> (a -> ?)) which is therefore the same type as (a -> (a -> (a -> ?))) which is... oops.
That would be the "infinite type", of course.
If you want to do this with functions that use a variable number of arguments of a single type, you'll probably want to use functions that take a list of values rather than individual arguments. Otherwise, you'll have to either write each version individually or use some arcane tricks involving advanced language features, neither of which is appealing in a simple case like this.
What you're asking for is not at all trivial. Haskell doesn't make it easy to deal with functions that apply functions with variable numbers of arguments. For example, the zip functions from Data.List come in separate variants for different numbers of arguments (zip, zip3, zip4, ...). Likewise, in Control.Monad there's liftM, liftM2, liftM3, ...
Basically, the most general type you can assign to a function with an unknown number of arguments is a -> b; a one-place truth function is Bool -> Bool (a = Bool, b = Bool), a two-place truth function is Bool -> (Bool -> Bool) (a = Bool, b = Bool -> Bool), three-place is Bool -> (Bool -> (Bool -> Bool)) (a = Bool, b = Bool -> (Bool -> Bool)), and so on. But there is no easy way you can look at the function you've been passed in to know what's the type on the right of the initial arrow.
One type of solution that can be made to work involves using type classes to define separate instances of the truth-table maker function for each argument function type. Sjoerd Visscher's answer in this thread is doing that for all function sizes by using a recursive instance definition (notice the recursive TruthTable a => TruthTable (Bool -> a) declaration). There may be other solutions that could be constructed using the Applicative type class.
I want to create a function apply that takes a function with an arbitrary amount of arguments as well as a list of integers, and returns the result of the function (Where each integer in the list is an argument in order.
I was thinking something like:
apply :: ([Int] -> Int) -> [Int] -> Int
apply f x:xs = apply (f x) xs
apply f [] = f
But I know this won't work because the type signature is wrong - the function doesn't take a list of ints, it just takes some amount of int arguments.
Additionally, when I get to the base case the f argument to apply should actually be an integer, violating the type signature anyway.
Does anyone know how to deal with this sort of problem?
I want to create a function apply that takes a function with an arbitrary amount of arguments as well as a list of integers,
Why do you want to do this? Perhaps your argument structure should be passed as a data structure, but so far you've over constrained the problem to ensure it won't produce an idiomatic Haskell solution.
You can do it with some fancy type classes
{-# LANGUAGE FlexibleInstances #-}
-- for ApplyType (Int -> r)
class ApplyType t where
apply :: t -> [Int] -> Int
instance ApplyType Int where
apply f _ = f
instance (ApplyType r) => ApplyType (Int -> r) where
apply f (x:xs) = apply (f x) xs
main :: IO ()
main = do print $ apply ((+) :: Int->Int->Int) [1, 2]
print $ apply ((\x y z w -> x*y - z`div`w) :: Int->Int->Int->Int->Int) [3,5,8,2]