Haskell join function inputs in list in specific order - haskell

Exercise
Hello every one!
I have been struggling to get this function working in the specific way they want.
I tried everything and the only output I could make was without the starting and ending point, eg: [((a,b),(b,c))]
Could someone please give me some help? I am stucked...
Update: type Point = (Float, Float)

Well since you got it working without the starting/ending point. An easy way to complete would be use your function but add the starting/ending point in the list in an inner function. So your interface is still same.
Another way using recursion, pattern matching and guards is:
-- assuming the inputs to be int as definition of point not given
solve x z [] = [(x,z)]
solve x z (y:ys)
| x == 0 = solve y z ys -- x ==0 to be replaced by null/empty condition on x
| null ys && z == 0 = [] -- z ==0 to be replaced by null/empty condition on z
| null ys = [(y, z)]
| otherwise = (x,y) : solve y z ys
Added a base case when the list is empty or start/end points not valid based on darthfennec comment.

Related

Square of even numbers in Haskell

I am trying to write a basic function in Haskell as shown below. My aim is provide the code to square only even numbers while odd numbers will stay same. Would you please help me regarding this issue.
square:: Int -> Int
square x = [ x*x | x <- [1..10], mod x 2 == 0 ]
regards
You are here filtering. You should determine if the number is even or odd and then square the number or not, this can be done in the yield part of the list comprehension.
But the type signature hints that you do not need to construct a list at all. You simply check if the parameter x is even, and if that is the case return x*x, otherwise return x:
square:: Int -> Int
square x = if even x then x*x else x
or through guards:
square:: Int -> Int
square x
| even x = x*x
| otherwise = x
One quite straightforward answer to your question is, you can inline a if statment directly into your list comprehension like so:
[ if even x then x * x else x | x <- [1..10] ]
This is possible since if is an expression in Haskell, meaning it evaluates to a value, so things like this are valid:
let _ = if 1 + 1 == 2 then "foo" else "bar"
It can also be good to look at this problem in another direction. List comprehensions can be quite nice, but sticking an if within it can get pretty messy. Willem's solution of factoring out the method is great, so let's look at other ways we can leverage it with your code:
-- This is the function we're trying to implement
evenSquares :: [Int] -> [Int]
-- We could start by noting that `if` expression has a nice name,
-- which can be factored out to make things look cleaner
-- Same implementation as Willem's
evenSquares xs = [ squareIfEven x | x <- xs ] where
squareIfEven x = if even x then x * x else x
-- List comprehensions are nice, but there's also another name for what we're doing,
-- which is mapping over a collection of values and applying a method
evenSquares xs = map squareIfEven xs where
squareIfEven x = if even x then x * x else x
-- Note how the `xs` is an argument to `evenSquares` and also the last argument to `map`
-- We can actually get rid of `xs` entirely via this rule:
-- https://wiki.haskell.org/Eta_conversion
evenSquares = map squareIfeven where
squareIfEven x = if even x then x * x else x
-- This one's a bit of a stretch, but conceptually quite useful
-- The idea of 'apply a method if a condition is true' can be expressed as a method
-- which takes a predicate method, a transformation method, and a value
-- We can leverage this ourselves to make `squareIfEven` more generic too
evenSquares = map (if' even square id) where
square x = x * x
if' pred fst snd x = if pred x then fst x else snd x
-- There's a bunch more solutions we can try, including things like `do` notation
-- This is just an idea of how you could look at your problem
-- Pick one which makes your solution clear and concise!

Haskell find divisors based on comprehension method

I need a little help understanding a comprehension method function.
compdivides :: Integer -> [Integer]
compdivides x
| x > 0 = [a | a <-[1..div x 2], mod x a == 0] ++ [x]
| otherwise = compdivides (abs x)
I understand that if x is positive we do the 3rd line otherwise the 4th line.
In the third line we check whether mod x a == 0 only then do we do everything else.
However, I cannot seem to understand this part a <-[1..div x 2] What exactly happens here?
Also, why do we do this at the end ++ [x] ? What exactly are we doing here anyways?
itemTotal :: [(String, Float)] -> [(String, Float)]
itemTotal [] = []
itemTotal [x] = [x]
I am having some trouble with this as well.
I understand that if the list is empty we simply return an empty list.
However, what are we saying here? itemTotal [x] = [x] That if the list only has one thing we simply return that one thing?
Thank you so much for the help!
However, I cannot seem to understand this part a <-[1..div x 2] What exactly happens here?
This is a generator of the list comprehension. The list comprehension:
[ a | a <- [1 .. div x 2 ], mod x a == 0 ]
will evaluate such that a takes each item in the list (so 1, 2, …, x/2), and in case mod x a == 0 (x is dividable by a), it will add a to the list.
Also, why do we do this at the end ++ [x] ? What exactly are we doing here anyways?
It appends x at the end of the list. This is done because a number x is always dividable by itself (x), since the a <- [1 .. div x 2] stops at div x 2, it will never check if x divides x.
The function will get stuck in an infinite loop for compdivides 0, so you might want to rewrite the function to cover this case as well.
However, what are we saying here? itemTotal [x] = [x] That if the list only has one thing we simply return that one thing?
Yes. Usually a pattern like itemTotal (x : xs) = x : itemTotal xs is used where we thus return a list where x is the first item, and we recurse on the tail of the list xs.
Your itemTotal function however only makes a copy of the list for the first two clauses. You thus can simply define itemTotal = id. Likely you will need to rewrite the function to determine the total of the items in the list.

What does myFunction(x:y:xs) mean in Haskell

I am new to Haskell and I came across one thing that I can seem to come around.So I have this function:
merge :: [Int] -> [Int]
merge xs = merged ++ padding
where padding = replicate (length xs - length merged) 0
merged = combine (filter (/= 0) xs)
combine (x:y:xs) | x == y = x * 2 : combine xs
| otherwise = x : combine (y:xs)
combine x = x
The problem is that I can't quite grasp what combine does.I did my research and found that
myFunction(x:xs) ...
represents that "x" is somehow the head of my list,and I can do stuff with it,right?Does that mean that in myFunction(x:y:xs) ...
"x" is the last element and "y" would be the second to the last element in xs?Is this right or am I terribly wrong?Also what about the ":" after "| x == y = x * 2",I learned that in Haskell ":" means appending a value to a list,but in this context I really can't quite understand what it does...Some help would be much apreciated.
x:y:xs is a pattern that says, "This is a list with at least 2 elements.We will call the first and second elements of this list x and y. The remaining sublist, which we will call xs may be empty or non-empty". That is, it represents both the list [1,2] and [1,2,3,4.....] but not [1].
Your second query can be answered by rewriting
| x == y = x * 2 : combine xs
as
| (x == y) = ((x * 2) : combine xs) for clarity. This is a standard if-else flow, except that Haskell does not require you to put those parentheses explicitly. Note that the 'pipes' are called guards and work similar to a switch-case statement in Java/C#.

Haskell Maze solving algorithm

I am trying to implement a maze solver based on the algorithm described in the below link in Haskell.
http://www.cs.bu.edu/teaching/alg/maze/
I am pretty new to haskell and functional programming, and I basically try to code the algorithm as described in the link, I tried to go through many other resources online but I am stuck in the part where the walking stops when the goal (It doesn't stop, it back tracks to the origin) is reached, and I am unable to unmark the bad positions in the maze.
The maze looks like
.########
.......#.
#.####..#
#.#######
...#.G...
##...####
#..######
my code is as follows
findPath :: Int->Int->Maze->(Bool,Maze)
findPath x y maze
| not (isSafe maze x y) = (False,maze)
| isChar maze x y 'G' = trace ("Solution: "++ show maze)(True,maze)
| isChar maze x y '#' = (False,maze)
| isChar maze x y '!' = (False,maze)
| fst walkNorth = (True,markedList)
| fst walkEast = (True,markedList)
| fst walkSouth = (True,markedList)
| fst walkWest = (True,markedList)
| otherwise = (False,unMarkedList)
where markedList = replaceCharInMaze maze x y '+'
unMarkedList = replaceCharInMaze maze x y '!'
walkNorth = findPath x (y-1) markedList
walkEast = findPath (x+1) y markedList
walkSouth = findPath x (y+1) markedList
walkWest = findPath (x-1) y markedList
the isSafe function just checks for bounds, the isChar is just character matching at a given x,y position and the replaceCharInMaze function replaces the character at the x,y position with the supplied character.
isSafe :: [String]->Int->Int->Bool
isSafe list x y
| y >= 0 && y < length (head list) && x >= 0 && x < length list && (isChar list xy '.' || isChar list x y 'G') = True
| otherwise = False
So, I have two problems
I am not able to persist the un-marking being done at the Otherwise case to the next recursion call, how do I go about persisting the state of the maze, so that even the un-marked state be part of the solution?
Then as the algorithm proceeds, It walks till the goal and comes back to the start, how to stop this from happening?
As I am new to Haskell and algorithms, I looked in to topics such has state monads, which seemed to be like the solution, but I am not quite sure about proceeding with it, I also tried looking into other stack overflow posts, but couldn't find anything that would help me.
The output for a maze obtained during the trace statement is as follows
+++#..###..#.
.#+++#+++.##.
####+#+#+#-##
...#+++#+#...
.#.####++.##.
.#G+++++#....
.############
....####.....
But it doesn't stop there it comes backtracks to the origin and prints the output as
+..#..###..#.
.#...#....##.
####.#.#.#.##
...#...#.#...
.#.####...##.
.#G.....#....
.############
....####.....
Here's what happens when you run your program with your example. The first four guards are clearly False, so not much happens up to that point. It evaluates walkNorth by recursing once, in order to find that fst walkNorth is also False. Then it evaluates walkEast, which takes a while, since eventually that leads to the goal. It finds that fst walkEast is True, so it returns (True,markedList). It's important to realise that the markedList in the returned pair has only been 'marked' once (hence there is a single '+' in your output). Lots of 'markings' have been happening on the way to the goal, but those aren't visible from where the program returns its output. Each time you pass a markedList into one of the walkXXX functions, you're essentially creating a new list, with an additional marking, which can only be seen in the function call you're passing it into. What you actually want is the maze with the markings at the point where it's been solved. At the end of the day, the walkXXX functions either return (False,maze) when walking in the XXX direction doesn't lead to the goal (because the 1st or 3rd guard evaluates to True), or (True,maze) if it does lead to the goal (the 2nd guard evaluates to True), in which case, maze at that point will have all the correct markings. So instead of returning markedList for the fst walkXXX cases, return snd walkXXX. i.e.
| fst walkNorth = (True,snd walkNorth)
| walkEast = (True,snd walkEast)
| walkSouth = (True,snd walkSouth)
| walkWest = (True,snd walkWest)
Your first question is a bit complicated. I think what you want is to change your walkXXX definitions to something very roughly like this:
walkNorth = findPath x (y-1) markedList
walkEast = findPath (x+1) y (replaceCharInMaze markedList x (y-1))
walkSouth = findPath x (y+1) (replaceCharInMaze (replaceCharInMaze markedList x (y-1)) (x+1) y)
and I'll let you fill in the last one. If you are walking east, you know that you've tried walking north and not found the goal, so you can unmark it, and so on. (This isn't quite going to work, at the very least because it will probably try to replace walls and characters outside of the maze, but the idea is there.)
You seem to be not yet accustomed to Haskell's lack of mutable state and frequent recursion. Some other things (I'm not certain about these): I don't think your otherwise case ever runs, and it doesn't really do anything -- try taking it out and see what happens; I also don't think the Trues in your (True,markedList) pairs ever have any effect -- try changing them to False.

Look up or insert new element to string list in Haskell

So I want to have a function that takes a String and a list as an argument, and checks if that element is already on the list, if it is, returns the same list, if it isnt, adds it to the list and returns it, 'im a begginer with haskell so heres what I have tried with no sucess:
check:: String ->[String] ->[String]
check x [] = []++[x]
check x (y:xs)
| x==y = (y:xs)
| otherwise = check x xs
Can someone point me the way ? thks
You can use the existing function elem
http://hackage.haskell.org/package/base-4.7.0.0/docs/Prelude.html#v:elem
check x ls
| x `elem` ls = ls
| otherwise = (x:ls)
If you want to do it completely on your own for learning purpose, I suggest re-implementing elem.
To implement check, we need to compare the elements of its second argument, l, one by one with its first argument, x. These elements of l that do not equal to x should be elements of the final result. If we find an element of l that equals x, there is no need to compare the rest of l with x.
So check can be implemented by using recursion like this
check x [] = [x]
check x l#(y:ys)
| x == y = l -- `l` is `y:ys`
| otherwise = y : check x ys
Explanation:
If the second argument is empty list, then the result is [x];
otherwise if the head of the second argument equals its first argument, the result should be the second argument;
finally, the head of its second argument should be part of the final result, and we should check the rest of its second argument recursively.

Resources