Can someone explain in detail the signature for this haskell function? - sorting

The signature for this function is confusing me and all information online is confusing me. Can someone explain to me the signature of the function and maybe give me an example?
sort3 :: Ord a => (a -> a -> Ordering) -> [a] -> [a]
sort3 cmp xs | length(xs) < 1 = xs
This is the error I'm getting.
Couldn't match expected type ‘a -> a -> Ordering’
with actual type ‘[t0]’
• In the first argument of ‘sort3’, namely ‘[]’
In the expression: sort3 []
In an equation for ‘it’: it = sort3 []
• Relevant bindings include
it :: [a] -> [a] (bound at <interactive>:2:1)

There are two arguments to this function:
sort3 :: Ord a => (a -> a -> Ordering) -> [a] -> [a]
The first argument is itself a function that takes two arguments: an orderable thing and an orderable thing (these are anything which is in the typeclass Ord) and it returns something of type Ordering.
The second argument is a list of these things, all of which are the exact same orderable thing that the first argument (itself a function) would take two of.
Finally, the sort3 function returns a list of that same orderable thing.
Now, GHCI is telling you that it expects the first argument to be what your signature says it should be (a function that itself takes two arguments and returns an Ordering), but you passed it an empty list instead:
Couldn't match expected type ‘a -> a -> Ordering’
with actual type ‘[t0]’
• In the first argument of ‘sort3’, namely ‘[]’
In the expression: sort3 []
In other words: "you told me your first argument would be (a -> a -> Ordering), but instead you've invoked the function like this sort3 [] and I can't interpret [] as function with this signature: (a -> a -> Ordering).

Related

How can I follow F# Lint's suggestion to use `id`

I am comparing two lists of thangs. Since I'm more familiar with Linq than F#, I did this:
let r1 = (rows1.Zip (rows2, fun r1 r2 -> rowComparer r1 r2)) .All (fun f -> f)
This raises two complaints from the F# linter.
Lint: If `rowComparer` has no mutable arguments partially applied then the lambda can be removed.
Lint: `fun x -> x` might be able to be refactored into `id`.
Of these, I could understand the latter, and tried this:
let r1 = (rows1.Zip (rows2, fun r1 r2 -> rowComparer r1 r2)) .All id
But this made the F# compiler complain:
This expression was expected to have type
'System.Func<bool,bool>'
but here has type
''a -> 'a'
Can someone say how this code can be more righteous?
I would suggest using the F# List or Seq modules instead of LINQ methods. Then you'll be able to use F# types like 'a -> 'a instead of System.Func<'a, 'a>, and you can pass id to the forAll function. If you could post a complete example, it would be easier to give you a complete answer, but I think something like this would be roughly equivalent to what you're doing with LINQ:
let compare (rowComparer: ('a * 'a) -> bool) rows =
Seq.zip rows >> Seq.map rowComparer >> Seq.forall id
This creates a function that takes two sequences and compares each value in the first to the corresponding value in the second, generating a sequence of booleans. It then returns true if all of the values in the sequence are true, otherwise it returns false. This is achieved using function composition and partial application to build a new function with the required signature.
You can then partially apply a row comparer function to create a specialized compare function for each of your scenarios, as follows:
let compareEqual = compare (fun (a,b) -> a = b)
compareEqual [0; 1; 2] [0; 1; 2] // true
compareEqual [0; 1; 2] [2; 1; 2] // false
You can supply the standard function id as an argument if you create an instance of System.Func with the correct number of generic type parameters from it. When employing a lambda expression, the F# compiler does that for you.
open System.Linq
let foo rowComparer (rows1 : seq<_>) (rows2 : seq<_>) =
(rows1.Zip (rows2, fun r1 r2 -> rowComparer r1 r2)).All(System.Func<_,_>(id))
// val foo :
// rowComparer:('a -> 'b -> bool) -> rows1:seq<'a> -> rows2:seq<'b> -> bool

DRY type annotation for QuickCheck properties

With QuickCheck, one can write parametrically polymorphic properties, like this:
associativityLaw :: (Eq a, Show a, Semigroup a) => a -> a -> a -> Property
associativityLaw x y z = (x <> y) <> z === x <> (y <> z)
This is just an example, as my actual properties are more complex, but it illustrates the problem well enough. This property verifies that for a type a, the <> operator is associative.
Imagine that I'd like to exercise this property for more than one type. I could define my test list like this:
tests =
[
testGroup "Monoid laws" [
testProperty "Associativity law, [Int]" (associativityLaw :: [Int] -> [Int] -> [Int] -> Property),
testProperty "Associativity law, Sum Int" (associativityLaw :: Sum Int -> Sum Int -> Sum Int -> Property)
]
]
This works, but feels unnecessarily verbose. I'd like to be able to simply state that for a given property, a should be [Int], or a should be Sum Int.
Something like this hypothetical syntax:
testProperty "Associativity law, [Int]" (associativityLaw :: a = [Int]),
testProperty "Associativity law, Sum Int" (associativityLaw :: a = Sum Int)
Is there a way to do this, perhaps with a GHC language extension?
My actual problem involves higher-kinded types, and I'd like to be able to state that e.g. f a is [Int], or f a is Maybe String.
I'm aware of this answer, but both options (Proxy and Tagged) seem, as described there, at least, too awkward to really address the issue.
You can use TypeApplications to bind type variables like this:
{-# LANGUAGE TypeApplications #-}
associativityLaw #[Int]
In the case you mentioned where you have a higher kinded type and you want to bind f a to [Int], you have to bind the type variables f and a separately:
fmap #[] #Int
For functions with more than one type variable, you can apply the args in order:
f :: a -> b -> Int
-- bind both type vars
f #Int #String
-- bind just the first type var, and let GHC infer the second one
f #Int
-- bind just the second type var, and let GHC infer the first one
f #_ #String
Sometimes the "order" of the type variables may not be obvious, but you can use :type +v and ask GHCi for more info:
λ> :t +v traverse
traverse
:: Traversable t =>
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> t a -> f (t b)
In standard haskell, the "order" of the type variables doesn't matter, so GHC just makes one up for you. But in the presence of TypeApplications, the order does matter:
map :: forall b a. (a -> b) -> ([a] -> [b])
-- is not the same as
map :: forall a b. (a -> b) -> ([a] -> [b])
For this reason, when working with highly parametric code, or you expect your users are going to want to use TypeApplications on your functions, you might want to explicitly set the order of your type vars instead of letting GHC define an order for you, with ExplicitForAll:
{-# LANGUAGE ExplicitForAll #-}
map :: forall a b. (a -> b) -> ([a] -> [b])
Which feels a lot like <T1, T2> in java or c#

Getting the first tuple of list of tuples in Haskell

I am trying to get the first element of a tuple for every tuple in a list using the following:
getRow :: [(Integer,Integer)] -> [(Integer,Integer)]
getRow (row:rows) = do
(fst(head (row)))
I thought if I could get the first element of every head of the list of tuples that it would return just the first element, but that wasnt the case.
Based on your description, your expected output should be a list of elements, not a list of tuples. Therefore, the first step is to change the signature to:
getRow :: [(Integer,Integer)] -> [Integer]
But why restrict to Integer, when the method can work for any type? Let's make it more general by doing this:
getRow :: [(a,b)] -> [a]
Now the algorithm itself. You have the right idea about using fst to get the first element. We will use this function, together with a list comprehension to do the job as follows:
getRow lst = [fst x | x <- lst]
This will go through the list, extract the first element from each tuple and return a list of the extracted elements. Putting it all together, we get this:
getRow :: [(a,b)] -> [a]
getRow lst = [fst x | x <- lst]
Demo
Of course, this is one of many possible ways to go about the problem. Another solution would be to use a foldr function to do the same thing, like so:
getRow2 :: [(a,b)] -> [a]
getRow2 lst = foldr (\x acc -> (fst x):acc) [] lst
You can start off with a good tutorial to learn about the basics of Haskell, and use Hackage for reference. However, #Eric is absolutely correct to say that in any paradigm, you need to figure out the steps first before you start to write the code.

Generic code does slow fibonacci while specific code is fast? [duplicate]

Consider the two following implementations of an infinite Fibonacci sequence:
fibsA :: Num a => [a]
fibsA = 0:1:(zipWith (+) fibsA (tail fibsA))
fibsB :: [Integer]
fibsB = 0:1:(zipWith (+) fibsB (tail fibsB))
In GHCI, executing fibsB !! k is much faster than executing fibsA !! k.
In particular, it seems that the values of fibsA are continuously recalculated (not memoized/stored).
Furthermore, when the type signature is omitted, GHCI's :t shows it to be [Integer], and the function performs accordingly.
This behavior also occurs in compiled code (ghc -O3 Fibs.hs).
Why is it the case that Integer is so much faster than Num a => a?
When you write fibsA :: Num a => [a], the compiler constructs what is essentially
fibsA :: NumDict a -> [a]
Where
data NumDict a = NumDict
{ (+) :: a -> a -> a
, (-) :: a -> a -> a
, (*) :: a -> a -> a
, negate :: a -> a
, abs :: a -> a
, signum :: a -> a
, fromInteger :: Integer -> a
}
Notice that Num a has moved from being a constraint to being an argument to the function. A typeclass is essentially just a lookup table for each type that implements the class. So for Num, you'd have by default
mkInteger_NumDict :: NumDict Integer
mkInteger_NumDict = NumDict
{ (+) = integer_plus
, (-) = integer_minus
, (*) = integer_mult
, ...
}
mkInt_NumDict :: NumDict Int
mkFloat_NumDict :: NumDict Float
mkDouble_NumDict :: NumDict Double
and these get automatically passed to a function using a typeclass when the instance is resolved. This means that our function fibsA essentially takes an argument. When you call it from GHCi, the defaulting rules kick in and pick Integer, but since it's being called this way it would look more like this internally:
{-# RecordWildCards #-} -- To reduce typing
fibsA :: NumDict a -> [a]
fibsA nd#(NumDict{..}) = fromInteger 0 : fromInteger 1 : zipWith (+) (fibsA nd) (tail $ fibsA nd)
Do you see the problem with this? It's still recursive, but now it has to make a function call each step of the way, reducing performance. If you wanted to make it really fast, a smart programmer would do
fibsA nd#(NumDict{..}) = fromInteger 0 : fromInteger 1 : zipWith (+) fibsA' (tail fibsA')
where fibsA' = fibsA nd
This at least allows memoization. However, a haskell binary can't really perform this optimization at runtime, that happens at compile time. So what you end up with is a slower recursive function. With fibsB, you're specifying the type concretely, there are no polymorphic constraints on it's type signature. The value fibsB has no implicit or explicit arguments, so when referred to it's a pointer to the same object in memory. fibsA is a pointer to a function, so when used recursively it returns new objects in memory, and has no memoization. This is why fibsB is faster than fibsA, only fibsB gets optimized because the compiler doesn't have to make it work for all Num, only Integer.
In addition to #bheklilr's thorough explanation: You can also make fibsA fast, if you perform the list sharing inside the function, making it non-recursive (hiding the recursion inside):
fibsA' :: Num a => [a]
fibsA' =
let f = 0:1:(zipWith (+) f (tail f))
in f

is there union and intersect Haskell Prelude implementation?

Is there in the Standard Prelude functions which implement the union and the intersection of sets ?
union :: (Eq a) => [a] -> [a] -> [a]
intersect :: (Eq a) => [a] -> [a] -> [a]
If no, may somebody can said if my implementation is efficient, (make good use of laziness and prelude function)
unionSet :: (Eq a) => [a] -> [a] -> [a]
unionSet as bs = foldl (\xs y -> if elem y xs then xs else xs ++ [y]) as bs
intersectSet :: (Eq a) => [a] -> [a] -> [a]
intersectSet as bs = let ns = [ a | a <- as, elem a bs] in [ b | b <- bs, elem b ns]
There are union and intersect functions on lists in the standard libraries, located in Data.List but not in the Prelude itself.
As far as efficiency goes, I'm going to say "no" to all of the above, both yours and the standard library's. There's really no way either can ever be efficient operations on a list with only an Eq constraint. That said, you may still find the implementation in Data.List informative--see the links above, which I've pointed directly to the relevant source.
Edit -- As a brief addendum for the sake of posterity, be sure to see Don's answer for what you actually want to use for this purpose, rather than the narrower question of "do these functions exist at all".
The base library provides list versions, as camccann points out. If you want something a bit more efficient, consider Data.Set, which provides:
union :: Ord a => Set a -> Set a -> Set a
intersection :: Ord a => Set a -> Set a -> Set a
with complexity O(n+m).

Resources