why my own 'index' function fails to run? - haskell

I am studying haskell language , doing some practices. Now I am attempting to implement my own 'index' function , meaning it can give the index of the given element within a list, but now my version fails to run , as the following
index' n (s:x)
| s/=n = 1+index' x
| otherwise = 0
main = print(index' 3 [1,2,3,5,6,7,9])
However , if simplifying the argument into one and set the target number in the guard , as the following , it run.
index' (s:x)
| s/=3 = 1+index' x
| otherwise = 0
main = print(index' [1,2,3,5,6,7,9])
I think there may be a elemental mistake in my understanding , and I need a help , please !

If index' takes two arguments, then it always takes two arguments. This includes the time when you call it recursively. Rather than
1+index' x
Consider
1+index' n x

To fix the question, as #chi has said, you should always start with a type declaration. In principle, Haskell can figure out the types, but if you make a mistake then Haskell will get it wrong too - very confusing. Also, you should be planning your function before you code. Without a type declaration, the nonsensical GHC error message is this:
Test.hs:2:1: error:
* Occurs check: cannot construct the infinite type: a ~ [a]
Expected type: [a] -> p
Actual type: a -> [a] -> p
* Relevant bindings include
index' :: [a] -> p (bound at Test.hs:2:1)
|
2 | index' n (s:x)
|
The type signature could be index' :: Int -> [Int] -> Int. This says that I give it an Int and an array of Int, and it returns an Int. That would do for your example, but is unnecessarily restrictive. The input types can be anything provided that we can do the equality test. Hence:
index' :: (Eq a) => a -> [a] -> Int
index' n (s:x)
| s/=n = 1+index' x
| otherwise = 0
main = print(index' 3 [1,2,3,5,6,7,9])
I am using Haskell Language Server (HLS) in Visual Studio Code. The error it gives me is that the pattern matches are not exclusive. GHC gives me the following (much improved) error, now that my type declaration is in:
Test.hs:3:16: error:
* Couldn't match expected type `Int'
with actual type `[[a]] -> Int'
* Probable cause: `(+)' is applied to too few arguments
In the expression: 1 + index' x
In an equation for index':
index' n (s : x)
| s /= n = 1 + index' x
| otherwise = 0
* Relevant bindings include
x :: [a] (bound at Test.hs:2:13)
s :: a (bound at Test.hs:2:11)
n :: a (bound at Test.hs:2:8)
index' :: a -> [a] -> Int (bound at Test.hs:2:1)
|
3 | | s/=n = 1+index' x
| ^^^^^^^^^^
So we have two problems.
Firstly, dealing with pattern matches. HLS says that I'm not handling _ [], that is to say irrespective of the value of n, the case where a zero length list is provided. So, we add that explicitly:
index' :: (Eq a) => a -> [a] -> Int
index' _ [] = 0
index' n (s:x)
| s/=n = 1+index' x
| otherwise = 0
main = print(index' 3 [1,2,3,5,6,7,9])
Now, HLS is highlighting the same code as GHC, and with the same error message. We haven't provided enough arguments. Let's fix that:
index' :: (Eq a) => a -> [a] -> Int
index' _ [] = 0
index' n (s:x)
| s/=n = 1+index' n x
| otherwise = 0
main :: IO ()
main = print(index' 3 [1,2,3,5,6,7,9])
That works. Although there's a problem of what happens if the value isn't found. We'd should consider using Maybe - a topic for another day.

Related

Recursive definition of the (!!)-function

So I tried to build the (!!) function as already defined in GHC.List recursively.
I want to extract the n-th element of a list and return that.
Here's what I got first:
taken0 :: [β] -> Int -> β -- but not recursive
βs `taken0` 0 = head βs
βs `taken0` n = last (take (n+1) βs)
This worked, but it wasn't recursive...
then I tried the following:
taken :: [γ] -> Int -> γ -- doesn't compile
taken γs 0 = head γs
taken γs 1 = head (tail γs)
taken γs n = head ( tail (takenth γs (n-1)) )
After some fixing I ended up with this:
taken :: [γ] -> Int -> [γ] -- works, but returns a list
taken γs 0 = γs
taken γs 1 = tail γs
taken γs n = tail (taken γs (n-1))
Which does indeed compile but is ugly to handle, it returns a list whoose first element is that one "entered" by n.
*Main> head ([0,1,2,3,4,5,6,7,8,9] `taken` 0) returns 0
*Main> head ([0,1,2,3,4,5,6,7,8,9] `taken` 1) returns 1
*Main> head ([0,1,2,3,4,5,6,7,8,9] `taken` 2) returns 2
etc.
Always returns the right (n-th element)
but I had to insert head before.
What I want is a function, which, although recursive, returns a single element instead of a list...
Is there a way to accomplish this without writing another function or using head everytime ?
like:
*Main> taken2 [5,8,6,0,2,5,7] 3 returns 0
thanks in advance !
taken :: [γ] -> Int -> [γ] -- works, but returns a list
taken γs 0 = γs
taken γs 1 = tail γs
taken γs n = tail (taken γs (n-1))
This is very close. There are three problems:
You have too many cases. You only need these two:
taken ys 0 = ...
taken ys n = ...
You want to return an element of the list, not a list. In particular, the first rule needs to return the first element of the list. One way to do this is with head:
taken ys 0 = head ys
Now we need to fix the second rule. We want to write this recursively, so we want to do something like this:
taken ys n = taken ?? ??
What do we put in place of the ??s? Well, we know that n is at least 1. And if we get down to 0, we can use the first rule to return the result. This suggests that the second parameter should be (n-1) as you already have tried.
We also know that the first element of ys isn't the right one to use, so we want to throw it away. To do this, we can use tail ys. Putting this all together we get
taken ys n = taken (tail ys) (n-1)
So it seems that the main mistake here is you were applying tail in the wrong place.
Notes
This solution isn't robust. It will cause an infinite recursion if you call it with a negative index. Handling for this case is left as an exercise for the reader.
You can use pattern matching instead of head and tail. For example, the first case can be written as
taken (y:_) 0 = y
I leave implementing the second case with pattern matching as an exercise for the reader.
Writing a recursive function on lists, you should almost always start by mirroring the recursive definition of the list type itself: a case for empty lists, and a case for a cons pair:
taken :: [γ] -> Int -> γ
taken [] n = _
taken (γ:γs) n = _
Note, the above syntax with underscore placeholders is actual Haskell syntax (for recent enough GHC), which will cause the compiler to print out errors like this asking you to fill in the blanks, and telling you about the pieces you have available to fill them in:
foo.hs:2:14: error:
• Found hole: _ :: γ
Where: ‘γ’ is a rigid type variable bound by
the type signature for:
taken :: forall γ. [γ] -> Int -> γ
at foo.hs:1:1-24
• In the expression: _
In an equation for ‘taken’: taken [] n = _
• Relevant bindings include
n :: Int (bound at foo.hs:2:10)
taken :: [γ] -> Int -> γ (bound at foo.hs:2:1)
|
2 | taken [] n = _
| ^
foo.hs:3:18: error:
• Found hole: _ :: γ
Where: ‘γ’ is a rigid type variable bound by
the type signature for:
taken :: forall γ. [γ] -> Int -> γ
at foo.hs:1:1-24
• In the expression: _
In an equation for ‘taken’: taken (γ : γs) n = _
• Relevant bindings include
n :: Int (bound at foo.hs:3:14)
γs :: [γ] (bound at foo.hs:3:10)
γ :: γ (bound at foo.hs:3:8)
taken :: [γ] -> Int -> γ (bound at foo.hs:2:1)
|
3 | taken (γ:γs) n = _
|
So the first hole we need to fill in is of type γ. However the only things we have available are the Int n, and making a recursive call to taken. Since the list is empty, recursing isn't going to help us; it'll just end up back at the same case we're in. And thinking about what our function is supposed to do, we can't get the nth element of an empty list no matter what n is. So we'll need to just call error here.
taken :: [γ] -> Int -> γ
taken [] n = error "Index out of range"
taken (γ:γs) n = _
The second hole is also of type γ, and GHC tells us:
• Relevant bindings include
n :: Int (bound at foo.hs:3:14)
γs :: [γ] (bound at foo.hs:3:10)
γ :: γ (bound at foo.hs:3:8)
taken :: [γ] -> Int -> γ (bound at foo.hs:2:1)
So we can obviously just use γ to appease the type checker, but logically which value we return should depend on n. If we're taking the 0th element of this list, well we've already got the head element decomposed as value γ due to our pattern match, so that'll be correct in that case. Lets try:
taken :: [γ] -> Int -> γ
taken [] n = error "Index out of range"
taken (γ:γs) n
| n == 0 = γ
| otherwise = _
Which gives us:
foo.hs:5:17: error:
• Found hole: _ :: γ
Where: ‘γ’ is a rigid type variable bound by
the type signature for:
taken :: forall γ. [γ] -> Int -> γ
at foo.hs:1:1-24
• In the expression: _
In an equation for ‘taken’:
taken (γ : γs) n
| n == 0 = γ
| otherwise = _
• Relevant bindings include
n :: Int (bound at foo.hs:3:14)
γs :: [γ] (bound at foo.hs:3:10)
γ :: γ (bound at foo.hs:3:8)
taken :: [γ] -> Int -> γ (bound at foo.hs:2:1)
|
5 | | otherwise = _
|
Same type of hole, same relevant bindings available. But we know that γ isn't the right answer, since we've already handled the case when it is. The answer we do want to return should be somewhere in γs, and we know we want to write this function recursively, so the obvious thing to do is insert a recursive call:
taken :: [γ] -> Int -> γ
taken [] n = error "Index out of range"
taken (γ:γs) n
| n == 0 = γ
| otherwise = taken γs _
foo.hs:5:26: error:
• Found hole: _ :: Int
• In the second argument of ‘taken’, namely ‘_’
In the expression: taken γs _
In an equation for ‘taken’:
taken (γ : γs) n
| n == 0 = γ
| otherwise = taken γs _
• Relevant bindings include
n :: Int (bound at foo.hs:3:14)
γs :: [γ] (bound at foo.hs:3:10)
γ :: γ (bound at foo.hs:3:8)
taken :: [γ] -> Int -> γ (bound at foo.hs:2:1)
|
5 | | otherwise = taken γs _
|
Now we're getting somewhere. The remaining hole is of type Int, and we have n :: Int available. Plugging that straight in is tempting, but doesn't make sense if we stop to think about what we're doing. Taking the nth element of the list (γ:γs) (which is the result we're supposed to be returning) when n \= 0 should be the same as taking the (n - 1)th element of γs, so:
taken :: [γ] -> Int -> γ
taken [] n = error "Index out of range"
taken (γ:γs) n
| n == 0 = γ
| otherwise = taken γs (n - 1)
No more holes! And this actually works. The only problem is that we don't handle negative values of n. It turns out that's actually sortof okay; for finite lists we eventually run off the end and hit the error "Index out of range" case, which is accurate. But it would be nicer to fail before iterating the whole list. So:
taken :: [γ] -> Int -> γ
taken [] n = error "Index out of range"
taken (γ:γs) n
| n == 0 = γ
| n < 0 = error "Negative index"
| otherwise = taken γs (n - 1)
I highly recommend this "hole driven development" style (whether you use actual hole syntax and get GHC to typecheck them or just do it yourself as you write the code). Let the structure of the types you're using guide the "shape" of the function you're writing (e.g. when writing a function on lists, use a case for [] and a case for (x:xs)), and then fill in the holes one at a time. Sometimes you'l need a different structure than this guides you towards, but very often not, and even when you do having started this approach and found out what the problems are gives you much better information for guessing the right structure.
Yes, a straightforward one is:
nth0 :: [a] -> Int -> a
nth0 (x:xs) i | i >= 1 = nth0 xs (i-1)
| i < 0 = error "Index less than zero"
| otherwise = x
nth0 [] i = error "Index too large"
So the recursive part is the nth0 xs (i-1). Here we thus perform recursion on the tail of the list xs, and with a decremented index i-1.
The base case is the otherwise (which fires in case i == 0), in which case we return the head of the list x.
The remaining cases cover the fact that the index could be negative, or that the index is greater than, or equal to the length of the list.

Type error in explicitly typed binding - Haskell

I've been struggling for like an hour to understand some things in higher order functions and now I am at the point that I cannot move any further because of this error:
hof :: [Integer] -> (Integer -> Integer)
isIn :: [Integer] -> Integer -> Integer
isIn [] s = 0
isIn [] _ = 0
isIn (h:t) s
| h == s = 0 {-<-------- error points here here-}
| otherwise = isIn(t) + 1
hof s = \n -> isIn s n
ERROR file:.\Lab2.hs:111 - Type error in explicitly typed binding
*** Term : isIn
*** Type : [Integer] -> Integer -> Integer -> Integer
*** Does not match : [Integer] -> Integer -> Integer
You are missing the second argument in the recursive call to isIn; it should be
| otherwise = isIn t s + 1
-- ^
While not an error, you also have a redundant base case; s and _ are both irrefutable patterns, so just isIn [] _ = 0 is sufficient.
Also not an error, but there is no difference between hof and isIn, as you can eta-reduce the definition to
hof s = isIn s
and again to
hof = isIn

Write the recursive function adjuster

Write the recursive function adjuster. Given a list of type
x, an int and an element of type x, either remove from the front of the
list until it is the same length as int, or append to the end of the list
until it is the same length as the value specified by the int.
expected:
adjuster [1..10] (-2) 2 -> *** Exception: Invalid Size
adjuster [1..10] 0 2 -> []
adjuster "apple" 10 ’b’ -> "applebbbbb"
adjuster "apple" 5 ’b’ -> "apple"
adjuster "apple" 2 ’b’ -> "le"
adjuster [] 3 (7,4) -> [(7,4),(7,4),(7,4)]
What i did:
adjuster (x:xs) count b
| count < 0 = error "Invalid Size"
| count == 0 = []
| count < length xs = adjuster xs (count-1) b
| otherwise = (adjuster xs (count-1) b):b
the error that I'm getting:
* Occurs check: cannot construct the infinite type: t ~ [t]
Expected type: [t]
Actual type: [[t]]
* In the expression: (adjuster xs (count - 1) b) : b
In an equation for `adjuster':
adjuster (x : xs) count b
| count < 0 = error "Invalid Size"
| count == 0 = []
| count < length xs = adjuster xs (count - 1) b
| otherwise = (adjuster xs (count - 1) b) : b
* Relevant bindings include
b :: [[t]] (bound at code01.hs:21:23)
adjuster :: [a] -> Int -> [[t]] -> [t] (bound at code01.hs:21:1)
I'm new in haskell.I'll really appreciate some help.
You are trying to construct a list within lists within lists and so on and so forth …
Why is this?
(:) :: a -> [a] -> [a]
The colon operator takes an element and a list of such elements as an argument and constructs a list from that (by prepending that element).
In your case if (adjuster ...) had type [a] then b must be of type [[a]], by line 4 which is the same as the end result, but line 3 says the type is [a] - which is different. This is what GHC tries to tell you.
How to fix it?
First of all, it is always a good advice to add a type signature to every top level function:
adjuster :: [a] -> Int -> a -> [a]
which should clean up your error-message and keep you honest, when implementing your function.
So how to fix this: - you could use b:adjuster xs (count-1) b but this would yield a result in the wrong order - so
choose a different operator: (++) and wrap the b inside a list.
| otherwise = (adjuster xs (count-1) b)++[b]
Now a few more hints:
turn on -Wall when you compile your file - this will show you that you missed the case of adjuster [] ...
using length is a relatively expensive operation - as it needs to traverse the full list to be calculated.
As an exercise - try to modify your function to not use length but only work with the base cases [] for list and 0 for count (here the function replicate might be helpful).
Here is another approach, without error handling
adjuster xs n v = tnr n $ (++) (replicate n v) $ tnr n xs
where tnr n r = take n $ reverse r
if you play with the signature, perhaps cleaner this way
adjuster n v = tnr . (++) (replicate n v) . tnr
where tnr = take n . reverse

Haskell Continuation passing style index of element in list

There's a series of examples I'm trying to do to practice Haskell. I'm currently learning about continuation passing, but I'm a bit confused as to how to implement a function like find index of element in list that works like this:
index 3 [1,2,3] id = 2
Examples like factorial made sense since there wasn't really any processing of the data other than multiplication, but in the case of the index function, I need to compare the element I'm looking at with the element I'm looking for, and I just can't seem to figure out how to do that with the function parameter.
Any help would be great.
first let me show you a possible implementation:
index :: Eq a => a -> [a] -> (Int -> Int) -> Int
index _ [] _ = error "not found"
index x (x':xs) cont
| x == x' = cont 0
| otherwise = index x xs (\ind -> cont $ ind + 1)
if you prefer point-free style:
index :: Eq a => a -> [a] -> (Int -> Int) -> Int
index _ [] _ = error "not found"
index x (x':xs) cont
| x == x' = cont 0
| otherwise = index x xs (cont . (+1))
how it works
The trick is to use the continuations to count up the indices - those continuations will get the index to the right and just increment it.
As you see this will cause an error if it cannot find the element.
examples:
λ> index 1 [1,2,3] id
0
λ> index 2 [1,2,3] id
1
λ> index 3 [1,2,3] id
2
λ> index 4 [1,2,3] id
*** Exception: not found
how I figured it out
A good way to figure out stuff like this is by first writing down the recursive call with the continuation:
useCont a (x:xs) cont = useCont a xs (\valFromXs -> cont $ ??)
And now you have to think about what you want valFromXs to be (as a type and as a value) - but remember your typical start (as here) will be to make the first continuation id, so the type can only be Int -> Int. So it should be clear that we are talking about of index-transformation here. As useCont will only know about the tail xs in the next call it seems natural to see this index as relative to xs and from here the rest should follow rather quickly.
IMO this is just another instance of
Let the types guide you Luke
;)
remarks
I don't think that this is a typical use of continuations in Haskell.
For once you can use an accumulator argument for this as well (which is conceptional simpler):
index :: Eq a => a -> [a] -> Int -> Int
index _ [] _ = error "not found"
index x (x':xs) ind
| x == x' = ind
| otherwise = index x xs (ind+1)
or (see List.elemIndex) you can use Haskells laziness/list-comprehensions to make it look even nicer:
index :: Eq a => a -> [a] -> Int
index x xs = head [ i | (x',i) <- zip xs [0..], x'== x ]
If you have a value a then to convert it to CPS style you replace it with something like (a -> r) -> r for some unspecified r. In your case, the base function is index :: Eq a => a -> [a] -> Maybe Int and so the CPS form is
index :: Eq a => a -> [a] -> (Maybe Int -> r) -> r
or even
index :: Eq a => a -> [a] -> (Int -> r) -> r -> r
Let's implement the latter.
index x as success failure =
Notably, there are two continuations, one for the successful result and one for a failing one. We'll apply them as necessary and induct on the structure of the list just like usual. First, clearly, if the as list is empty then this is a failure
case as of
[] -> failure
(a:as') -> ...
In the success case, we're, as normal, interested in whether x == a. When it is true we pass the success continuation the index 0, since, after all, we found a match at the 0th index of our input list.
case as of
...
(a:as') | x == a -> success 0
| otherwise -> ...
So what happens when we don't yet have a match? If we were to pass the success continuation in unchanged then it would, assuming a match is found, eventually be called with 0 as an argument. This loses information about the fact that we've attempted to call it once already, though. We can rectify that by modifying the continuation
case as of
...
(a:as') ...
| otherwise -> index x as' (fun idx -> success (idx + 1)) failure
Another way to think about it is that we have the collect "post" actions in the continuation since ultimately the result of the computation will pass through that code
-- looking for the value 5, we begin by recursing
1 :
2 :
3 :
4 :
5 : _ -- match at index 0; push it through the continuation
0 -- lines from here down live in the continuation
+1
+1
+1
+1
This might be even more clear if we write the recursive branch in pointfree style
| otherwise -> index x as' (success . (+1)) failure
which shows how we're modifying the continuation to include one more increment for each recursive call. All together the code is
index :: Eq a => a -> [a] -> (Int -> r) -> r -> r
index x as success failure
case as of
[] -> failure
(a:as') | x == a -> success 0
| otherwise -> index x as' (success . (+1)) failure

Haskell: Recursion with a polymorphic equality function

Ok so we have not learned polymorphic functions yet, but we still have to write this code.
Given:
nameEQ (a,_) (b,_) = a == b
numberEQ (_,a) (_,b) = a == b
intEQ a b = a == b
member :: (a -> a -> Bool) -> a -> [a] -> Bool
I added:
member eq x ys | length ys < 1 = False
| head(ys) == x = True
| otherwise = member(x,tail(ys))
but i get errors about not being the correct type as well as some other stuff. We have to see if an element exists in from some type. So we have those 2 types above. Some examples given:
phoneDB = [("Jenny","867-5309"), ("Alice","555-1212"), ("Bob","621-6613")]
> member nameEQ ("Alice","") phoneDB
True
> member nameEQ ("Jenny","") phoneDB
True
> member nameEQ ("Erica","") phoneDB
False
> member numberEQ ("","867-5309") phoneDB
True
> member numberEQ ("","111-2222") phoneDB
False
> member intEQ 4 [1,2,3,4]
True
> member intEQ 4 [1,2,3,5]
False
not exactly sure what i need to do here. Any help or documentation on this would be great. Thanks!
Various things (I'm not going to write out the full answer as this is homework):
length ys < 1 can be more simply expressed as null ys
You don't need brackets around function arguments. head(ys) is more commonly written as head ys
You can, if you want, turn the top case and the other two into pattern matches rather than guards. member eq x [] = ... will match the empty case, member eq x (y:ys) = ... will match the non-empty case.
You are using == for comparison. But you're meant to use the eq function you're given instead.
You are bracketing the arguments to member as if this was Java or similar. In Haskell, arguments are separated by spaces, so member(x,(tail(ys)) should be member x (tail ys).
Those errors you gloss over "about not being the correct type as well as some other stuff" are important. They tell you what's wrong.
For example, the first time I threw your code into ghc I got:
Couldn't match expected type `a -> a -> Bool'
against inferred type `(a1, [a1])'
In the first argument of `member', namely `(x, tail (ys))'
In the expression: member (x, tail (ys))
In the definition of `member':
member eq x ys
| length ys < 1 = False
| head (ys) == x = True
| otherwise = member (x, tail (ys))
Well, when I look at it that's straightforward - you've typed
member(x,tail(ys))
When you clearly meant:
member x (tail ys)
Commas mean something in Haskell you didn't intend there.
Once I made that change it complained again that you'd left off the eq argument to member.
The error after that is tougher if you haven't learned about Haskell typeclasses yet, but suffice it to say that you need to use the passed-in eq function for comparing, not ==.
Since the parameters a in member :: (a -> a -> Bool) -> a -> [a] -> Bool
don't derive Eq, you can't use == to compare them,
but instead have to use the given function eq.
Therefore your code might look like this:
member :: (a -> a -> Bool) -> a -> [a] -> Bool
member eq x ys
| length ys < 1 = False
| eq x (head ys) = True
| otherwise = member eq x (tail ys)
Only problem with this is, that length still requires to evaluate the entire List,
so you could reach a a better performance writing:
member' :: (a -> a -> Bool) -> a -> [a] -> Bool
member' eq x (y:ys)
| eq x y = True
| otherwise = member' eq x ys
member' _ _ [] = False
With the use of any you can simplify it even more:
member'' :: (a -> a -> Bool) -> a -> [a] -> Bool
member'' f a = any (f a)

Resources