Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to write some code in ocaml that parses the following c code for predefined functions
main {
x = function1(3);
x = function2(x,2);
}
So here is my ocaml code:
match expr with
|Bool(b) ->( match b with
|true -> (*do things*)
|false -> (*do things*) )
|Call(f, args) ->( match f with
| function1(x) -> (*do things with x*)
| function2(x,n) -> (*do things with x and n*)
|_ -> failwith "not implemented yet " )
For the time being, let's assume the language I'm parsing only has two functions, I would like to retrieve the arguments in the C code in order to use them in my ocaml program but I get a syntax error at the line containing the match with sth()
Removing the parentheses and the arguments make the program run but this is not what I want, I need to arguments...
I don't understand what is wrong with my matching could someone please explain the right syntax to me?
Thanks in advance
The pattern matching only match type constructors.
The first thing to do is to write down the type you want to match :
type typ =
| Bool of bool
| Function1 of int
| Function2 of int * int
Then your fonction will look like this one (combining all the differents case inside a single one match case):
let eval
: typ -> unit (* The function signature *)
= fun t ->
match t with
| Bool true -> print_endline "true"
| Bool false -> print_endline "false"
| Function1 number -> print_endline (string_of_int number)
| Function2 (n1, n2) -> print_endline (string_of_int (n1 + n2))
Related
I have a type synonym for a puzzle defined as shown here:
type Cell = Int
type Board = Array Cell
type Puzzle = forall r.
{ board::Board
, meta::
{ metaData :: {|r}
, metaBoard :: (Array {|r})
}
}
I have also included the idea that a strategy takes a Puzzle and returns it wrapped in one of three states
type Strategy = Puzzle -> (Stateful Puzzle)
data Stateful a =
Advancing a
| Stable a
| Finished a
Finally, I have a function that brings us back in line (a bit) with how Either works. The idea being that eventually I can start composing strategies until the finished state is reached.
advanceOrFinish :: (Stateful Puzzle) -> (Stateful Puzzle)
advanceOrFinish (Advancing puzzle)
| isSolvedOrInvalid puzzle.board = Finished puzzle
| otherwise = Advancing puzzle
advanceOrFinish (Stable puzzle)
| isSolvedOrInvalid puzzle.board = Finished puzzle
| otherwise = Advancing puzzle
advanceOrFinish (Finished puzzle) = Finished puzzle
The problem is that I'm getting this error:
The type variable r, bound at
src/SC.purs:23:15 - 29:4 (line 23, column 15 - line 29, column 4)
has escaped its scope, appearing in the type
{ board :: Array Int
, meta :: { metaBoard :: Array (Record r7)
, metaData :: Record r7
}
}
The same function without Stateful (while useless) doesn't have this issue. So this is fine:
advanceOrFinish :: Puzzle -> Puzzle
advanceOrFinish puzzle
| isSolvedOrInvalid puzzle.board = puzzle
| otherwise = puzzle
What is this error trying to tell me?
type Puzzle = forall r. ... doesn't mean what you think it means.
If you have a variable:
p :: Puzzle
And then you want to do something with that variable, like:
b = p.board
At that moment, when you're referring to p by name, you get to choose a type r, and then the variable p must somehow "become" of that type, meaning that p.meta.metaData :: {|r}.
And this happens every time you access the variable p. Each time you choose some type r (and these could be different types every time), and each time the field p.meta.metaData would have to be of that type.
Quite obviously, this could not reasonably work. Quite obviously, this is not what you meant.
forall means "I will work for all types" - that's literally in the name. The consumer chooses which type, not the implementer.
What you probably meant was to have a Puzzle with a type parameter, so that whoever creates an instance of Puzzle can choose the type at that moment, and then the instance of Puzzle will go on with that type.
The syntax for doing that is this:
type Puzzle r =
{ board::Board
, meta::
{ metaData :: {|r}
, metaBoard :: (Array {|r})
}
}
Here r is called "type parameter" of Puzzle.
Then, whenever you refer to Puzzle, you have to say what r is in that case, for example:
foo :: Puzzle (a :: Int) -> Int
foo p = p.meta.metaData.a
bar :: Puzzle (x :: String) -> Unit
bar _ = unit
And if you don't care what it is, it can be generic too:
advanceOrFinish :: forall r. Puzzle r -> Puzzle r
advanceOrFinish puzzle
| isSolvedOrInvalid puzzle.board = puzzle
| otherwise = puzzle
I want it to use library-defined partialfunc more convenient, or write callback with partial pattern-matching.
like this,
partialMaybe :: forall a b. (Partial => a -> b) -> a -> Maybe b
I couldn't find similar in some major libraries.
How to define it? or already defined in libs?
data ABC a = A a | B a | C a
f1 = someHigherOrderFunc $ partialMaybe \(A a) -> someFunc a -- if not 'A', return Nothing.
-- same as
f2 = someHigherOrderFunc $ case _ of A a -> Just $ someFunc a
_ -> Nothing -- requires line break, seems syntax redundant...
using: purescript 0.11.6
Edit:
I did it...
partialMaybe :: forall a b. (Partial => a -> b) -> a -> Maybe b
partialMaybe f a = runPure $ catchException (const $ pure Nothing) (Just <<< unsafePartial f <$> pure a)
this is...umm...very ugly. it's not.
'Failed pattern match' exception is thrown by the purescript.
so I think it should be able to handle by purescript.
Can't do it?
If you want an exception if a case is missed, use Partial. If you want otherwise, use Maybe or Either or another appropriate sum type.
You can catch the exception thrown from a failed pattern match. There is no way for a failed pattern match to not throw an exception.
I want to write a function that accepts values of a custom class myType, and returns myType option. Not sure if my problem is with signature, content or return values.
For example, I've tried to write the following (it's simplified and have no real meaning):
let rec myFunc (t:myType) myType option =
let t2 = myFunc t in
match t2 with
| None -> None
| _ -> t
And I'm getting the following compilation error:
Error: This pattern matches values of type 'a option
but a pattern was expected which matches values of type 'b -> 'c -> 'd
Not sure what's wrong with my syntax or where I'm misunderstanding OCaml.
I only see a missing colon and Some:
let rec myFunc (t:myType): myType option =
let t2 = myFunc t in
match t2 with
| None -> None
| _ -> Some t
Slightly streamlined version:
let rec myFunc (t:myType): myType option =
match myFunc t with
| None -> None
| _ -> Some t
This question already has answers here:
Haskell - Maybe Either
(4 answers)
Closed 8 years ago.
I have this assignment where I am unsure where to start. So one of the things is to do a
maybe to either conversion with this signature:
maybeEither:: Maybe a -> Either () a
and the other is of course the opposite
eitherMaybe:: Either () a -> Maybe a
so when you call one of the other they will cancel eachother out.
Now I don't really know where to begin here... Can someone help?
Extra question: How would I convert a function for example (Int->a) -> a and a -> (Int->a)
Like since in the second example you really can't give the function as a parameter to the function that converts, Im not sure how that would go.
First of all, these are not typeclasses, they're data types. If you're unfamiliar with the difference, I would recommend reading the relevant chapters in Learn You a Haskell.
To solve this particular problem, you just need to pattern match on the different constructors:
maybeEither :: Maybe a -> Either () a
maybeEither Nothing = ???
maybeEither (Just a) = ???
And
eitherMaybe :: Either () a -> Maybe a
eitherMaybe (Left x) = ???
eitherMaybe (Right y) = ???
You just need to fill in the the ???s and you're done.
For your extra question, remember that the signature a -> (Int -> a) is the same as a -> Int -> a, since -> is right associative.
Actually it's very simple, just follow the types to see what you get. The type signature of maybeEither suggests that it takes Maybe a as input.
Maybe is defined like this:
data Maybe a = Just a | Nothing
Also, from the type sigature, you can get that maybeEither gives Either () a as the output for the function.
Either type constructor is defined like this:
data Either a b = Left a | Right b
Now, replace a with () and you will get:
Either () b = Left () | Right b
Or you can replace your type variables to make it clear,
Either () a = Left () | Right a
Now, the implementation of the function is pretty straightforward.
maybeEither :: Maybe a -> Either () a
maybeEither (Just x) = ??? -- fill these
maybeEither Nothing = ???
You can follow the same approach for your other function.
In at least some of the ML family languages, you can define records on which you can perform pattern matching e.g. http://learnyouahaskell.com/making-our-own-types-and-typeclasses - the basic idea is that you define a record type with named fields, a constructor is automatically created with those fields as parameters so you can create records of that type, and an extractor is automatically created with those fields as parameters so you can pattern match on records of that type.
Scala goes a step further and allows the fields stored in the record, the constructor parameters and the extractor parameters to be decoupled from each other e.g. http://daily-scala.blogspot.com/2009/11/overloaded-unapply.html - in this it is living up to its goal of supporting both object-oriented and functional programming. (Object-oriented languages of course normally allow stored fields and constructor parameters to be decoupled, though they don't normally have extractors.)
Are there any other languages that have pattern matching and allow such decoupling?
Has anything been written about the pros and cons of such decoupling?
I admit that I don't have 100% of the background required to understand your question, but I can say that F# has a feature called "Active Patterns" that it seems could be used to build the same functionality that your daily-scala link demonstrates.
Is that in the neighborhood of what you're looking for?
No, F# also provides that feature.
Examples in the second article can be implemented using Partial Active Patterns:
let (|String|_|) = function "s" -> Some "yay" | _ -> None
let (|Int|_|) = function 1 -> Some "hmm" | _ -> None
let (|StringList|_|) = function "x" -> Some [1; 2; 3] | _ -> None
let (|IntList|_|) = function 1 -> Some ["one"; "two"] | _ -> None
match 1 with
| Int s -> printfn "%O" s
| _ -> printfn "Unmatched"
match "s" with
| String s -> printfn "%O" s
| _ -> printfn "Unmatched"
match "x" with
| StringList [x; y; z] -> printfn "%O" (x, y, z)
| _ -> printfn "Unmatched"
match 1 with
| IntList [x; y] -> printfn "%O" (x, y)
| _ -> printfn "Unmatched"
Active Patterns is a powerful technique, you can even write it in a recursive way. Its combination with pattern matching provides a convenient toolkit for destructuring data. However, pattern matching is inexhaustive so you have to use wildcard(_) as the last pattern.
For reference, Don Syme (the inventor of F#) wrote a paper about F#'s "Active Patterns": Extensible Pattern Matching Via a Lightweight Language Extension – Syme, et al.
There is a long history of first class patterns in typed functional languages.
In Haskell land, we use the -XViewPatterns extension for programmatic patterns.
The first true view patterns go back to Phil Wadler's 1987 paper on views