Modifying a list using recursion - haskell

I have a list with elements of type LocalType (defined below), I wish to modify this list in function of which subtptype the element is belonging too.
An element of type End stays in the list of type End. For an element of type Prl (End Bar End), the first End shall stay in the list, the second End shall be appended to the list.
E.g [End, (Prl s Bar ss)] -> [End, s, ss]
E.g [End, End Bar End] -> [End, End, End]
This is how I thought of implementing it,
sepTimes :: [LocalType] -> [LocalType]
sepTimes(x:[]) = [x]
sepTimes(x:xs)
| x == End = sepTimes (x:xs)
| x == (Prl s Bar ss) = do
sepTimes (s:xs)
sepTimes (ss:xs)
As the error messages states, I am unable to retrive the elements s and ss corresponding to End and End in the example of Prl (End Bar End).
app\Sequents.hs:44:17: error: Variable not in scope: s :: LocalType
|
44 | | x == (Prl s Bar ss) = do
| ^
app\Sequents.hs:44:23: error:
* Variable not in scope: ss :: LocalType
* Perhaps you meant `xs' (line 42)
|
44 | | x == (Prl s Bar ss) = do
| ^^
app\Sequents.hs:45:19: error: Variable not in scope: s :: LocalType
|
45 | sepTimes (s:xs)
| ^
app\Sequents.hs:46:19: error:
* Variable not in scope: ss :: LocalType
* Perhaps you meant `xs' (line 42)
|
46 | sepTimes (ss:xs)
| ^^
Here are the defined datatypes :
data Seperator = Bar | BackAmpersand
deriving (Show, Eq, Ord, Read)
data LocalType = End
| Prl LocalType Seperator LocalType
deriving (Eq, Ord, Read)

You're confusing equality checks with pattern matching. Intuitively, all of the following should be the same:
f :: Either Int Char -> String
f (Left i) = show i
f (Right c) = [c]
f :: Either Int Char -> String
f x = case x of
Left i -> show i
Right c -> [c]
f :: Either Int Char -> String
f x
| x==Left i = show i -- what?
| x==Right c = [c]
But actually, only the first two are equivalent, the last one doesn't work. Why? You can't match a variable out of an equality statement. That may work in some logical languages where the equality is propositional, but Haskell's == operator is simply boolean: it takes two fully known values and tells you whether or not they're exactly the same. I.e., in order to be able to write x==Left i, the variable i must already be defined.

Related

Simulating non-deterministic choice through the List Monad

I'm trying to write an evaluation function for a language that I am working on in which non-determinism can be permitted within an if-block, called a selection block. What I'm trying to achieve is the ability to pick an if/selection statement from the block whose guard is true and evaluate it but it doesn't matter which one I pick.
From searching, I found an example that performs in a similar way to what I would like to achieve through modelling coinflips. Below is my adapation of it but I'm having issue in applying this logic to my problem.
import Control.Monad
data BranchType = Valid | Invalid deriving (Show)
data Branch = If (Bool, Integer) deriving (Show, Eq)
f Valid = [If (True, 1)]
f Invalid = [If (False, 0)]
pick = [Invalid, Invalid, Valid, Invalid, Valid]
experiment = do
b <- pick
r <- f b
guard $ fstB r
return r
s = take 1 experiment
fstB :: Branch -> Bool
fstB (If (cond, int)) = cond
main :: IO ()
main = putStrLn $ show $ s -- shows first branch which could be taken.
Below is my ADT and what I have been trying to make work:
data HStatement
= Eval HVal
| Print HVal
| Skip String
| Do HVal [HStatement]
| If (HVal, [HStatement])
| IfBlock [HStatement] -- made up of many If
| Select [HStatement] -- made up of many If
deriving (Eq, Read)
fstIf :: HStatement -> Bool
fstIf (If (cond, body)) = if hval2bool cond == True
then True
else False
h :: Env -> HStatement -> IOThrowsError ()
h env sb = do
x <- g env sb
guard $ fstIf x -- Couldn't match expected type ‘HStatement’ with actual type ‘[HStatement]’
-- after guard, take 1 x then evaluate
g :: Env -> HStatement -> IOThrowsError [HStatement]
g env (Select sb) = mapM (\x -> f env x) sb
f :: Env -> HStatement -> IOThrowsError HStatement
f env (If (cond, body)) = evalHVal env cond >>= \x -> case x of
Bool True -> return $ If (Bool True, body)
Bool False -> return $ If (Bool False, body)
The error I receive is the following : Couldn't match expected type ‘HStatement’ with actual type ‘[HStatement]’ at the guard line. I believe the reason as to why the first section of code was successful was because the values were being drawn from List but in the second case although they're being drawn from a list, they're being drawn from a [HStatement], not something that just represents a list...if that makes any sort of sense, I feel like I'm missing the vocabulary.
In essence then what should occur is given a selection block of n statement, a subset of these are produced whose guards are true and only one statement is taken from it.
The error message is pretty clear now that you have some types written down. g returns IOThrowsError [HStatement], so when you bind its result to x in h, you have an [HStatement]. You then call fstIf, which expects a single HStatement, not a list. You need to decide how to handle the multiple results from g.

How do I use (#) operator in Haskell as I get parse error on input?

I am new to Haskell and I am trying to calculate the maximum segment sum,
(#) :: Int -> Int -> Int
x # y = 0 `max` (x + y)
mss2 :: [Int] -> Int
mss2 = maximum . scanr (#) 0
The error is
No Modules Loaded for (#)
I found this snippet in Richard Bird's text.
What am I missing here?
Are there other ways to declare/overload the operators, is my approach wrong?
It appears that in the context of that book, (#) is being used as a stand-in for some binary operator such as (+) or (<>), even though this is not actually legal Haskell syntax†.
For questions about Haskell syntax, it’s helpful to consult the Haskell 2010 Report.
In Ch. 2 Lexical Structure, under §2.2 Lexical Program Structure, you can find # in the grammar of symbols that may appear in an operator name:
symbol → ascSymbol | uniSymbol⟨special | _ | " | '⟩
ascSymbol → ! | # | $ | % | & | ⋆ | + | . | / | < | = | > | ? | #
| \ | ^ | | | - | ~ | :
And §2.4 Lexical Structure: Identifiers and Operators defines valid operator names to include such symbols:
varsym → ( symbol⟨:⟩ {symbol} )⟨reservedop | dashes⟩
consym → ( : {symbol} )⟨reservedop⟩
However, the subscript in angle brackets denotes a “difference” or exclusion, so this disallows a list of reserved identifiers. Under the production reservedop you can find that # appears in that list:
reservedop → .. | : | :: | = | \ | | | <- | -> | # | ~ | =>
The reason is that the # symbol denotes an “as” pattern, described in §3.17.2.8 Informal Semantics of Pattern Matching:
Matching an as-pattern var#apat against a value v is the result of matching apat against v, augmented with the binding of var to v.
As patterns are very useful for controlling the sharing of values and making certain definitions more concise, e.g.:
-- | Merge two sorted lists.
merge :: (Ord a) => [a] -> [a] -> [a]
-- ‘as0’ & ‘bs0’ denote the original input lists.
-- ‘as’ & ‘bs’ denote their tails.
merge as0#(a : as) bs0#(b : bs) = case compare a b of
-- ‘as0’ passes along the same list cell;
-- repeating ‘a : as’ would allocate a /new/ cell.
GT -> b : merge as0 bs
_ -> a : merge as bs0
merge [] bs0 = bs0
merge as0 [] = as0
Therefore, the definition:
x # y = 0 `max` (x + y)
Or more conventionally written x#y = …, is equivalent to defining two variables referring to the same value, which furthermore is defined recursively:
x = 0 `max` (x + y)
y = x
Without the type signature Int -> Int -> Int, this definition would be accepted, defining x, y :: (Ord a, Num a) => a, but attempting to evaluate either variable would produce an infinite loop, since this is “unproductive” recursion.
The solution is to use a non-reserved symbol as your operator name instead, such as <#> or +..
† I can’t find a citation for this, but it’s possible that GHC used to accept this syntax, even though it was also disallowed by the Haskell 98 Report which was current at the time the first edition of this book came out, and that this example code just wasn’t updated for the second edition.

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.

Haskell: Nested List Comprehension

I have an assignment for school, that I need help on. So far I've created two types, Argument and Predicate, per the assignment instructions.
In this project, I have to create a list, titled 'context', of arguments (or, objects) in the world AND a list of facts about these objects, in a list titled 'facts'.
So, for instance, the context list has arguments "john" and "boston" and then in our fact list we can create a predicate with the function fly to have a fact "fly john to_boston" where to denotes that John flies to Boston.
For the final step of the project, we have to be able to ask Haskell: "qWhere fly john" and have Haskell search the context list for "john" and use that to search the list of facts for "fly" and "john" in order to eventually return "to_boston" or "boston."
I understand that this is nested list comprehension, but I don't understand how to get Haskell to return "to_boston" once it has "fly john". I'll include bits of the code below (scroll to the bottom for what I've been working on):
{-# LANGUAGE MultiParamTypeClasses #-}
-- GL TYPES
data Type = HUMN | -- human
ANIM | -- animate
ORGN | -- organic
ORGZ | -- organization
PHYS | -- physical object
ARTF | -- artifact
EVNT | -- event
PROP | -- proposition
INFO | -- information
SENS | -- sensation
LOCA | -- location
TIME | -- time period
ATTD | -- attitude
EMOT | -- emotion
PPTY | -- property
OBLG | -- obligation
RULE -- rule
deriving (Show, Eq, Enum)
-- CUSTOM DATA TYPES
data Argument = Argument { ttype :: Type, value :: String }
deriving (Show, Eq)
data Predicate = Predicate { lemma :: String
, arguments :: [Argument] }
deriving (Show, Eq)
type Context = [Argument]
-- CREATE SEMANTICALLY TYPED ARGUMENTS AS FOLLOWS
date :: String -> Argument
date s = Argument { ttype = TIME, value = s }
time :: String -> Argument
time s = Argument { ttype = TIME, value = s }
location :: String -> Argument
location s = Argument { ttype = LOCA, value = s }
human :: String -> Argument
human s = Argument { ttype = HUMN, value = s }
phys :: String -> Argument
phys s = Argument { ttype = PHYS, value = s }
artifact :: String -> Argument
artifact s = Argument { ttype = ARTF, value = s }
animate :: String -> Argument
animate s = Argument { ttype = ANIM, value = s }
-- CREATE ENTITIES/PPs AS FOLLOWS
may15 = date "May 15, 2014"
sevenAM = time "7:00"
sandiego = location "San Diego"
john = human "John"
mary = human "Mary"
boston = location "Boston"
ball = phys "ball"
car = artifact "car"
cat = animate "cat"
mouse = animate "mouse"
to_boston = to boston
context = [
may15,
sevenAM,
sandiego,
john,
mary,
boston,
ball,
cat,
mouse
]
-- HELPER FUNCTIONS
getValue :: Argument -> String
getValue c = value c
getType :: Argument -> Type
getType c = ttype c
isType :: Argument -> Type -> Bool
isType c t = (ttype c == t)
-- CREATE PREPOSITIONS AS FOLLOWS
to :: Argument -> Predicate
to x = Predicate { lemma = "to", arguments = [x] }
-- CREATE VERBS AS FOLLOWS
class Fly a b where
fly :: a -> b -> Predicate
instance Fly Argument Argument where
fly x y = Predicate { lemma = "fly", arguments = [x, y] }
--overwrite lemma,
instance Fly Argument Predicate where
fly x y = Predicate { lemma = lemma y
, arguments = [x, arguments y !! 0] }
facts = [fly john to_boston, fly mary to_boston]
-- THIS IS WHERE I'M STUCK\/
qWhere :: (Argument -> Argument -> Predicate) -> Argument
-> [[Argument]]
qWhere f x = [[arguments z | ]| z <- facts, x `elem` (arguments z)]
-- THIS RETURNS THE ENTIRE STATEMENT:
qWhere f x = [[arguments z | ]| z <- facts, x `elem` (arguments z)]
I don't think you need/want nested list comprehension. First you need to understand that list comprehension is really just syntactic sugar.
But we can use let ... in syntax to make use of multiple list comprehensions. A solution could look like this:
qWhere :: (Argument -> Argument -> Predicate)
-> Argument
-> [[Argument]]
qWhere f x = case find (== x) context of
Just e ->
-- first we get all facts about e.g. john
let personFacts = [z | z <- facts, e `elem` arguments z]
-- then we get all facts when we apply f to john and
-- any other arguments that exist in john
actionFacts = fmap (f e) (concatMap arguments personFacts)
-- and extract all arguments of those facts
actionArgs = concatMap arguments actionFacts
-- and can finally build the actual list of facts,
-- reduced by checking if the argument "john" is in one of our
-- actionArgs where we applied f to
in map arguments [z | z <- personFacts, e `elem` actionArgs]
Nothing -> []
You might need to import Data.List.

Haskell Binary Tree with only chars

Lets say I make my tree like this
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
But I want to make a tree that uses only chars I don't need it to be template. I know my tree will use only chars if I make it like the one above I can't make if dataOfNode == ')' in a function because It says that it is a [char] type and it expects [a] type.
How to make a tree that would use only chars or is there a way to make this type of check dataOfNode == ')' with this type of tree that I gave. Can you give me a short example of a function that let's say check if the data in this node is the sign ')' ?
Edit:
As requested I am posting the function that I would like to make `
buildTreeHelper :: (Ord a) => String -> a -> Int -> String -> Tree a -> Tree a
buildTreeHelper str blank turn path t
| str == [] = t
| front == '(' = buildTreeHelper (tail str) blank 1 ('L':path) (expandTree (reverse path) blank t)
| front == ')' = buildTreeHelper (tail str) blank 2 (tail path) t
| turn == 1 = buildTreeHelper (tail str) blank 2 (tail path) (expandTree (reverse path) front t)
| turn == 2 = buildTreeHelper (tail str) blank 3 ('R':path) (expandTree (reverse path) front t)
| turn == 3 = buildTreeHelper (tail str) blank 2 (tail path) (expandTree (reverse path) front t)
where
front = head str
Logically it is not finished but also I can't use it because it takes a string which I divade char by char. That's why I am sure I want to make my Tree only from chars so I can replace type a with type char at the begining of the function. It has other mistakes too but I think the main idea is clear.
You easily could replace your type definition with
data Tree = EmptyTree | Node Char Tree Tree deriving (Show, Read, Eq)
or specialise just your function defining it as
buildTreeHelper :: String -> Char -> Int -> String -> Tree Char -> Tree Char

Resources