Haskell parse error on input '|' - haskell

I'm getting the following error:
parse error on input '|'
with my code:
makeMove :: Player -> Board -> Maybe Board
makeMove p b | hasWinner b == Nothing = getMove p rb ri
where rb = gameTree p b
ri = minimax p rb
ros2int (i' :> ri') = i'
rb2b (b':rbs') = b
getMove p (r:rs) (i:is) = let bs = map rb2b rs
is = map ros2int is
idx = elemIndex (maximum' is) is
res (Nothing) = Nothing
res (Just x) = Just ((bs)!!x)
in res idx
| otherwise = Nothing
However I suppose this would be caused by tabs interference usually but I checked and I only used spaces so that couldn't be the problem. Could anyone help me out on this?
Thanks in advance!
Best regards,
Skyfe.

The where clause should be after all guards:
fun a b
| one = ...
| oterwise = ...
where ....

Related

How can I parse the left associative notation of SKI combinator calculus

I've tried a bunch of stuff, and they always seem to result in one of 2 things:
Program hangs forever (infinite left recursion)
Right associativity (right recursion)
My only idea now is just to parse from the end of the string instead of the beginning, but do to the list nature of haskell's strings, that would require either traversing the list for every charachter, or parsing a reversed string. Neither option sound good.
Here's the relevant bits from my current code (which is right associative). I've tried left recursion, but it just ends up in an infinite loop.
{-# LANGUAGE PatternGuards #-}
data C = S | K | I deriving (Read,Show,Eq)
data T = N T T | C C deriving Eq
parse :: String -> T
parse s | (e,rest) <- parseStep s = if rest == "" then e else N e (parse rest)
parseStep :: String -> (T,String)
parseStep ('(':s) = parseParen s
parseStep (c:s) = (C $ read [c],s)
parseParen (c:')':s) = (C $ read [c],s)
parseParen s = parseStep s
Figured it out thanks to luqui's comment:
parse :: String -> T
parse = foldTs . parseList
foldTs :: [T] -> T
foldTs (t:ts) = foldl N t ts
parseList :: String -> [T]
parseList "" = []
parseList s = let (x,r) = parseStep s in x:parseList r
parseStep :: String -> (T,String)
parseStep ('(':s) = let (ts,r) = parseParenList s in (foldTs ts,r)
parseStep (c:s) = (C $ read [c],s)
parseParenList :: String -> ([T],String)
parseParenList (')':s) = ([],s)
parseParenList s =
let
(x,r) = parseStep s
(xs,r') = parseParenList r
in (x:xs,r')

Exception: Prelude.head: empty list in Haskell

I can't figure out why I'm getting this error. I have already read all the questions already asked about this error and I don't have any of those issues. Can someone please help. The comments are the hard code for the given example so we can use a top-down approach. When I get done with a function I comment out the hard code. I have only implemented the first 2 functions. In ghci when you run the file, type 'main', if it prints true the code is working. When I test both functions separately they return true but together they return the above error.
import Data.List ((\\), sort)
type Board = [[Int]]
inputBoard :: Board
inputBoard =
[[5,3,0, 0,7,0, 0,0,0],
[6,0,0, 1,9,5, 0,0,0],
[0,9,8, 0,0,0, 0,6,0],
[8,0,0, 0,6,0, 0,0,3],
[4,0,0, 8,0,3, 0,0,1],
[7,0,0, 0,2,0, 0,0,6],
[0,6,0, 0,0,0, 2,8,0],
[0,0,0, 4,1,9, 0,0,5],
[0,0,0, 0,8,0, 0,7,9]]
solvedBoard :: Board
solvedBoard =
[[5,3,4, 6,7,8, 9,1,2],
[6,7,2, 1,9,5, 3,4,8],
[1,9,8, 3,4,2, 5,6,7],
[8,5,9, 7,6,1, 4,2,3],
[4,2,6, 8,5,3, 7,9,1],
[7,1,3, 9,2,4, 8,5,6],
[9,6,1, 5,3,7, 2,8,4],
[2,8,7, 4,1,9, 6,3,5],
[3,4,5, 2,8,6, 1,7,9]]
type Coords = (Int,Int)
type BoardElement = (Coords,Int)
inputBoardElements :: [BoardElement]
inputBoardElements =
[((0,0),5),((0,1),3),((0,4),7),((1,0),6),((1,3),1),((1,4),9),((1,5),5),
((2,1),9),((2,2),8),((2,7),6),((3,0),8),((3,4),6),((3,8),3),((4,0),4),
((4,3),8),((4,5),3),((4,8),1),((5,0),7),((5,4),2),((5,8),6),((6,1),6),
((6,6),2),((6,7),8),((7,3),4),((7,4),1),((7,5),9),((7,8),5),((8,4),8),
((8,7),7),((8,8),9)]
inputBoardEmpty :: [Coords]
inputBoardEmpty =
[(0,2),(0,3),(0,5),(0,6),(0,7),(0,8),(1,1),(1,2),(1,6),(1,7),(1,8),
(2,0),(2,3),(2,4),(2,5),(2,6),(2,8),(3,1),(3,2),(3,3),(3,5),(3,6),
(3,7),(4,1),(4,2),(4,4),(4,6),(4,7),(5,1),(5,2),(5,3),(5,5),(5,6),
(5,7),(6,0),(6,2),(6,3),(6,4),(6,5),(6,8),(7,0),(7,1),(7,2),(7,6),
(7,7),(8,0),(8,1),(8,2),(8,3),(8,5),(8,6)]
solvedBoardElements :: [BoardElement]
solvedBoardElements =
[((0,0),5),((0,1),3),((0,2),4),((0,3),6),((0,4),7),((0,5),8),((0,6),9),
((0,7),1),((0,8),2),((1,0),6),((1,1),7),((1,2),2),((1,3),1),((1,4),9),
((1,5),5),((1,6),3),((1,7),4),((1,8),8),((2,0),1),((2,1),9),((2,2),8),
((2,3),3),((2,4),4),((2,5),2),((2,6),5),((2,7),6),((2,8),7),((3,0),8),
((3,1),5),((3,2),9),((3,3),7),((3,4),6),((3,5),1),((3,6),4),((3,7),2),
((3,8),3),((4,0),4),((4,1),2),((4,2),6),((4,3),8),((4,4),5),((4,5),3),
((4,6),7),((4,7),9),((4,8),1),((5,0),7),((5,1),1),((5,2),3),((5,3),9),
((5,4),2),((5,5),4),((5,6),8),((5,7),5),((5,8),6),((6,0),9),((6,1),6),
((6,2),1),((6,3),5),((6,4),3),((6,5),7),((6,6),2),((6,7),8),((6,8),4),
((7,0),2),((7,1),8),((7,2),7),((7,3),4),((7,4),1),((7,5),9),((7,6),6),
((7,7),3),((7,8),5),((8,0),3),((8,1),4),((8,2),5),((8,3),2),((8,4),8),
((8,5),6),((8,6),1),((8,7),7),((8,8),9)]
main :: IO ()
main = print (sudoku inputBoard == solvedBoard)
sudoku :: Board -> Board
sudoku [] = []
sudoku b =
let bde = fst (toElements b)
cd = snd (toElements b)
allboards = sudokuElements [bde] cd
in fromElements (head allboards)
--sudoku b
--| b == inputBoard = solvedBoard
--| otherwise = error "sudoku not implemented"
sudokuElements :: [[BoardElement]] -> [Coords] -> [[BoardElement]]
sudokuElements a [] = a
sudokuElements [] _ = []
sudokuElements (be:bes) (cd:cds) =
let xs = validVals be cd
temp = [[(cd,x)] | x <- xs]
in sudokuElements temp cds
-- | head bes == inputBoardElements && empty == inputBoardEmpty =
-- [solvedBoardElements]
-- | otherwise = error "sudokuElements not implemented"
validVals :: [BoardElement] -> Coords -> [Int]
validVals bes rc
| bes == tail solvedBoardElements && rc==(8,6) = [1]
| bes \\ solvedBoardElements == [] = [1..9]
| otherwise = []
toElements :: Board -> ([BoardElement],[Coords])
toElements b
| b==inputBoard = (inputBoardElements, inputBoardEmpty)
| otherwise = error "toElements not implemented"
fromElements :: [BoardElement] -> Board
fromElements bes
| sort bes == solvedBoardElements = solvedBoard
| otherwise = error "fromElements not implemented"
The issue is that allBoards/the call to sudokuElements is returning an empty list.
Without seeing the entire program, it's hard to give you an exact reason why this might be.
I recommend avoiding the use of head in general as it is a partial function. Instead, use pattern matching.
In your case, this
fromElements (head allBoards)
can be rewritten as
case allBoards of
[] -> error "allBoards returned an empty list." -- Or whatever
(first:_) -> fromElements first

'where' inside other expression

I can use let inside other expression.
foo n = (let a = True in (\x -> a)) 3
foo' n | n == 1 = let a = True in a
| n /= 1 = False
But I can't do the same with where
foo n = ((\x -> a) where a = True) 3
foo' n | n == 1 = a where a = True
| n /= 1 = False
1:20: parse error on input `where'
Is it really impossible in haskell or just my mistake?
let is an expression while where is a clause. where is bound to syntactic constructs, let can be used anywhere expressions can.
You could of course write it like this:
foo n = ((\x -> a)) 3 where a = True
foo' n | n == 1 = a
| n /= 1 = False
where a = True
or like this:
foo n = (\a -> (\x -> a) 3) True
You need to put the where clause at the end:
foo n = ((\x -> a)) 3
where a = True
foo' n | n == 1 = a
| n /= 1 = False
where a = True
The difference is that let is an expression, whereas where requires some other construct to be bound to. See let vs where
let ... in ... is for introducing name bindings in an expression.
where is convenience syntax for giving local auxiliary definitions along with an equation. You can only use it as part of an equation (at the end), not in the middle of an arbitrary expression.
Their usage is not the same.
The claim that let is an expression is a bit off, it seems to me; in a do block it is a statement, though we say that there it abbreviates let ... in. The thing to say, I think, is
let_in_ :: Statement -> Expression -> Expression
_where_ :: Statement -> Statement -> Statement
Thus the first part of a let is a statement and can be modified by a where. So for example
foo n = (let a = b where b = True in (\x -> a)) 3
bip = do
let a = b where b = let c = d where d = True in c
return a
Similarly we can maybe say something like this:
case_of_ :: Expression -> [Statement] -> Expression
so that e.g.
z x = case even x of
True -> d where d = x + 1
False -> w - 1 where w = let a = x in a + 1

haskell parse error on input '<-'

there is a question really confused me when i am running this piece of code
data Tree a = Nil | Node a (Tree a) (Tree a)
type IntTree = Tree Int
type Counter = State Int
withCounter::Int -> Counter a -> a
withCounter init f = fst(runState f init)
nextCount::Counter Int
nextCount = do
n <- get
put (n+1)
return n
incTree::IntTree -> IntTree
incTree tree = withCounter 1 (IncTree' tree)
incTree' Nil = return 0
incTree' (Node l e r) = do
newl <- incTree' l
n <- nextCount
newr <- incTree' r
return (Node newl (e+n) newr)
the error is as following:
parse error on input '<-'
and it appears to be raised at line 27, that is 'n <- nextCount'
does anyone know why i am getting this error ? thanks !
As you appear not to have copied and pasted your code directly, the answer is probably that you are mixing tab characters and spaces.
Do not use tabs: indent using spaces only.

How To Change List of Chars To String?

In F# I want to transform a list of chars into a string. Consider the following code:
let lChars = ['a';'b';'c']
If I simply do lChars.ToString, I get "['a';'b';'c']". I'm trying to get "abc". I realize I could probably do a List.reduce to get the effect I'm looking for but it seems like there should be some primitive built into the library to do this.
To give a little context to this, I'm doing some manipulation on individual characters in a string and when I'm done, I want to display the resulting string.
I've tried googling this and no joy that way. Do I need to just bite the bullet and build a List.reduce expression to do this transformation or is there some more elegant way to do this?
Have you tried
System.String.Concat(Array.ofList(lChars))
How many ways can you build a string in F#?
Here's another handful:
let chars = ['H';'e';'l';'l';'o';',';' ';'w';'o';'r';'l';'d';'!']
//Using an array builder
let hw1 = new string [|for c in chars -> c|]
//StringBuilder-Lisp-like approach
open System.Text
let hw2 =
string (List.fold (fun (sb:StringBuilder) (c:char) -> sb.Append(c))
(new StringBuilder())
chars)
//Continuation passing style
let hw3 =
let rec aux L k =
match L with
| [] -> k ""
| h::t -> aux t (fun rest -> k (string h + rest) )
aux chars id
Edit: timings may be interesting? I turned hw1..3 into functions and fed them a list of 500000 random characters:
hw1: 51ms
hw2: 16ms
hw3: er... long enough to grow a beard? I think it just ate all of my memory.
Didn't see this one here, so:
let stringFromCharList (cl : char list) =
String.concat "" <| List.map string cl
"" is just an empty string.
FSI output:
> stringFromCharList ['a'..'d'];;
val it : string = "abcd"
EDIT:
Didn't like this syntax coming back to this so here's a more canonically functional one:
['a'..'z'] |> List.map string |> List.reduce (+)
['a';'b';'c'] |> List.fold_left (fun acc c -> acc ^ (string c)) ""
Edited:
Here is yet another funny way to do your task:
type t =
| N
| S of string
static member Zero
with get() = N
static member (+) (a: t, b: t) =
match a,b with
| S a, S b -> S (a+b)
| N, _ -> b
| _, N -> a
let string_of_t = function
|N -> ""
|S s -> s
let t_of_char c = S (string c)
['a'; 'b'; 'c'] |> List.map t_of_char |> List.sum |> string_of_t
Sadly, just extending System.String with 'Zero' member does not allow to use List.sum with strings.
Edited (answer to Juilet):
Yes, you are right, left fold is slow. But i know more slow right fold :) :
#r "FSharp.PowerPack"
List.fold_right (String.make 1 >> (^)) ['a';'b';'c'] ""
and of course there is fast and simple:
new System.String(List.to_array ['1';'2';'3'])
And i used 'sprintf' seems to me easier:
let t = "Not what you might expect"
let r = [ for i in "aeiou" -> i]
let q = [for a in t do if not (List.exists (fun x -> x=a) r) then yield a]
let rec m = function [] -> "" | h::t -> (sprintf "%c" h) + (m t)
printfn "%A" (m q)
The following solution works for me:
let charList = ["H";"E";"L";"L";"O"]
let rec buildString list =
match list with
| [] -> ""
| head::tail -> head + (buildString tail)
let resultBuildString = buildString charList
[|'w'; 'i'; 'l'; 'l'|]
|> Array.map string
|> Array.reduce (+)
or as someone else posted:
System.String.Concat([|'w'; 'i'; 'l'; 'l'|])

Resources