Persistent: Convert Text to Key - mysql

I'm using persistent and persistent-mysql. I have a Monad SqlM
type SqlM a = SqlPersist (ResourceT IO) a)
Inside my function
testFun :: T.Text -> SqlM ()
testFun someId = ...
I can query the Database by using
entity <- selectFirst [SomeField ==. someId]
But I would like to select entitys by ID. I have to convert/pack someId to the Key - Type. I know this isn't the way to do it, but i tried:
entity <- get $ Key { unKey = PersistInt64 (read $ T.unpack someId) }
this fails with:
Couldn't match type `PersistEntityBackend
(Entity (DBTableGeneric backend0))'
with `Database.Persist.GenericSql.Raw.SqlBackend'
The type variable `backend0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Expected type: Key (Entity (DBTableGeneric backend0))
Actual type: KeyBackend
Database.Persist.GenericSql.Raw.SqlBackend
(Entity (DBTableGeneric backend0))
In the second argument of `($)', namely
`Key {unKey = PersistInt64 (read $ T.unpack someId)}'
Any ideas what's going wrong?

I usually use fromPathPiece for this kind of conversion. As for your error message, you can probably just add a type signature to clarify to the compiler what types you're working with.

Related

Unable to define a parser in Haskell: Not in scope: type variable ‘a’

I am trying to define a parser in Haskell. I am a total beginner and somehow didn't manage to find any solution to my problem at all.
For the first steps I tried to follow the instructions on the slides of a powerpoint presentation. But I constantly get the error "Not in scope: type variable ‘a’":
type Parser b = a -> [(b,a)]
item :: Parser Char
item = \inp -> case inp of
[] -> []
(x:xs) -> [(x:xs)]
error: Not in scope: type variable ‘a’
|
11 | type Parser b = a -> [(b,a)]
| ^
I don't understand the error but moreover I don't understand the first line of the code as well:
type Parser b = a -> [(b,a)]
What is this supposed to do? On the slide it just tells me that in Haskell, Parsers can be defined as functions. But that doesn't look like a function definition to me. What is "type" doing here? If it s used to specify the type, why not use "::" like in second line above? And "Parser" seems to be a data type (because we can use it in the type definition of "item"). But that doesn't make sense either.
The line derives from:
type Parser = String -> (String, Tree)
The line I used in my code snippet above is supposed to be a generalization of that.
Your help would be much appreciated. And please bear in mind that I hardly know anything about Haskell, when you write an answer :D
There is a significant difference between the type alias type T = SomeType and the type annotation t :: SomeType.
type T = Int simply states that T is just another name for the type Int. From now on, every time we use T, it will be replaced with Int by the compiler.
By contrast, t :: Int indicates that t is some value of type Int. The exact value is to be specified by an equation like t = 42.
These two concepts are very different. On one hand we have equations like T = Int and t = 42, and we can replace either side with the other side, replacing type with types and values with values. On the other hand, the annotation t :: Int states that a value has a given type, not that the value and the type are the same thing (which is nonsensical: 42 and Int have a completely different nature, a value and a type).
type Parser = String -> (String, Tree)
This correctly defines a type alias. We can make it parametric by adding a parameter:
type Parser a = String -> (String, a)
In doing so, we can not use variables in the right hand side that are not parameters, for the same reason we can not allow code like
f x = x + y -- error: y is not in scope
Hence you need to use the above Parser type, or some variation like
type Parser a = String -> [(String, a)]
By contrast, writing
type Parser a = b -> [(b, a)] -- error
would use an undeclared type b, and is an error. At best, we could have
type Parser a b = b -> [(b, a)]
which compiles. I wonder, though, is you really need to make the String type even more general than it is.
So, going back to the previous case, a possible way to make your code run is:
type Parser a = String -> [(a, String)]
item :: Parser Char
item = \inp -> case inp of
[] -> []
(x:xs) -> [(x, xs)]
Note how [(x, xs)] is indeed of type [(Char, String)], as needed.
If you really want to generalize String as well, you need to write:
type Parser a b = b -> [(b, a)]
item :: Parser Char String
item = \inp -> case inp of
[] -> []
(x:xs) -> [(xs, x)]

How to serialize function type to json in haskell?

data Task = Task
{ id :: String
, description :: String
, dependsOn :: [String]
, dependentTasks :: [String]
} deriving (Eq, Show, Generic, ToJSON, FromJSON)
type Storage = Map String Task
s :: Storage
s = empty
addTask :: Task -> Storage -> Storage
addTask (Task id desc dep dept) = insert id (Task id desc dep dept)
removeTask :: String -> Storage -> Storage
removeTask tid = delete tid
changes = [addTask (Task "1" "Description" [] []), removeTask "1"]
main = putStrLn . show $ foldl (\s c -> c s) s changes
Suppose I have the following code. I want to store changes list in a json file. But I don't know how to do that with Aeson, aside probably from writing a custom parser and there must be a better way to do that obviously. Like maybe using language extension to derive (Generic, ToJSON, FromJSON) for addTask and removeTask etc...
EDIT. For all people that say "You can't serialize function".
Read the comments to an answer to this question.
Instance Show for function
That said, it's not possible to define Show to actually give you more
? detail about the function. – Louis Wasserman May 12 '12 at 14:51
Sure it is. It can show the type (given via Typeable); or it can show some of the inputs and outputs (as is done in QuickCheck).
EDIT2. Okay, I got that I can't have function name in serialization. But can this be done via template Haskell? I see that aeson supports serialization via template Haskell, but as newcomer to Haskell can't figure out how to do that.
Reading between the lines a bit, a recurring question here is, "Why can't I serialize a function (easily)?" The answer -- which several people have mentioned, but not explained clearly -- is that Haskell is dedicated to referential transparency. Referential transparency says that you can replace a definition with its defined value (and vice versa) without changing the meaning of the program.
So now, let's suppose we had a hypothetical serializeFunction, which in the presence of this code:
foo x y = x + y + 3
Would have this behavior:
> serializeFunction (foo 5)
"foo 5"
I guess you wouldn't object too strenuously if I also claimed that in the presence of
bar x y = x + y + 3
we would "want" this behavior:
> serializeFunction (bar 5)
"bar 5"
And now we have a problem, because by referential transparency
serializeFunction (foo 5)
= { definition of foo }
serializeFunction (\y -> 5 + y + 3)
= { definition of bar }
serializeFunction (bar 5)
but "foo 5" does not equal "bar 5".
The obvious followup question is: why do we demand referential transparency? There are at least two good reasons: first, it allows equational reasoning like above, hence eases the burden of refactoring; and second, it reduces the amount of runtime information that's needed, hence improving performance.
Of course, if you can come up with a representation of functions that respects referential transparency, that poses no problems. Here are some ideas in that direction:
printing the type of the function
instance (Typeable a, Typeable b) => Show (a -> b) where
show = show . typeOf
-- can only write a Read instance for trivial functions
printing the input-output behavior of the function (which can also be read back in)
creating a data type that combines a function with its name, and then printing that name
data Named a = Named String a
instance Show (Named a) where
show (Named n _) = n
-- perhaps you could write an instance Read (Map String a -> Named a)
(and see also cloud haskell for a more complete working of this idea)
constructing an algebraic data type that can represent all the expressions you care about but contains only basic types that already have a Show instance and serializing that (e.g. as described in the other answer)
But printing a bare function's name is in conflict with referential transparency.
Make a data type for your functions and an evaluation function:
data TaskFunction = AddTask Task | RemoveTask String
deriving (Eq, Show, Generic, ToJSON, FromJSON)
eval :: TaskFunction -> Storage -> Storage
eval (AddTask t) = addTask t
eval (RemoveTask t) = removeTask t
changes = [AddTask (Task "1" "Description" [] []), RemoveTask "1"]
main = putStrLn . show $ foldl (\s c -> c s) s (eval <$> changes)

How to read value of property depending on an argument

How can I get the value of a property given a string argument.
I have a Object CsvProvider.Row which has attributes a,b,c.
I want to get the attribute value depending on property given as a string argument.
I tried something like this:
let getValue (tuple, name: string) =
snd tuple |> Seq.averageBy (fun (y: CsvProvider<"s.csv">.Row) -> y.```name```)
but it gives me the following error:
Unexpected reserved keyword in lambda expression. Expected incomplete
structured construct at or before this point or other token.
Simple invocation of function should look like this:
getValue(tuple, "a")
and it should be equivalent to the following function:
let getValue (tuple) =
snd tuple |> Seq.averageBy (fun (y: CsvProvider<"s.csv">.Row) -> y.a)
Is something like this is even possible?
Thanks for any help!
The CSV type provider is great if you are accessing data by column names statically, because you get nice auto-completion with type inference and checking.
However, for a dynamic access, it might be easier to use the underlying CsvFile (also a part of F# Data) directly, rather than using the type provider:
// Read the given file
let file = CsvFile.Load("c:/test.csv")
// Look at the parsed headers and find the index of column "A"
let aIdx = file.Headers.Value |> Seq.findIndex (fun k -> k = "A")
// Iterate over rows and print A values
for r in file.Rows do
printfn "%A" (r.Item(aIdx))
The only unfortunate thing is that the items are accessed by index, so you need to build some lookup table if you want to easily access them by their name.

Yesod custom field of type [Double]

I want to create a custom field in Yesod that is a text field with a JSON array of doubles. However I keep getting type errors. My current attempt is:
doubleListField :: RenderMessage master FormMessage => Field sub master [Double]
doubleListField = Field
{ fieldParse = parseHelper $ Right . decodeUtf8 . parse json
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="number" :isReq:required="" value="Hey">
|]
}
(Correct whitespace found: https://gist.github.com/4394850)
I'm currently failing with:
Couldn't match expected type `Data.ByteString.Internal.ByteString'
with actual type `[Text]
-> m0 (Either (SomeMessage master0) (Maybe Text))'
In the second argument of `($)', namely `parseHelper $ Right'
In the `fieldParse' field of a record
In the expression:
Field
{fieldParse = parse json $ parseHelper $ Right,
fieldView = \ theId name attrs val isReq
-> toWidget (\ _render_a5Cg -> ...)}
fieldView I'll modify and I know how to go about that but I'm flummoxed about how fieldParse should look. Thanks!
Please note that your code does not match the error.
The fieldParse function should turn the user submitted data into a Haskell structure. As you discovered, there is a parseHelper function that simplifies creating the field.
The type of parseHelper is essentially (Text -> Either FormMessage a) -> X, where X is the exact type of fieldParse. That is, once you pass one argument to the helper, you get a correct fieldParse.
The argument to parseHelper should be a function, that recieves a Text input and returns Right [Double] or Left FormMessage if parsing failed.
Depending on what you use to parse the JSON, the function could look like this (assuming existence of a few more helpers that you will most likely have to write):
fieldParse = parseHelper $ \text -> case parse json text of
Right value | isListOfDoubles value -> Right $ extractListOfDoubles value
_ -> Left "Wrong input"

Order of fields in a type for FileHelpers

I'm reading a simple CSV file with Filehelpers - the file is just a key, value pair. (string, int64)
The f# type I've written for this is:
type MapVal (key:string, value:int64) =
new()= MapVal("",0L)
member x.Key = key
member x.Value = value
I'm missing something elementary here, but FileHelpers always assumes the order of fields to be the reverse of what I've specified - as in Value, Key.
let dfe = new DelimitedFileEngine(typeof<MapVal>)
let recs = dfe.ReadFile(#"D:\e.dat")
recs |> Seq.length
What am I missing here?
The order of primary constructor parameters doesn't necessarily determine the order that fields occur within a type (in fact, depending on how the parameters are used, they may not even result in a field being generated). The fact that FileHelpers doesn't provide a way to use properties instead of fields is unforunate, in my opinion. If you want better control over the physical layout of the class, you'll need to declare the fields explicitly:
type MapVal =
val mutable key : string
val mutable value : int64
new() = { key = ""; value = 0L }
new(k, v) = { key = k; value = v }
member x.Key = x.key
member x.Value = x.value
The library uses the order of the field in the declaration, but looks like that F# words different, in the last the last stable version of the library you can use the [FieldOrder(1)] attribute to provide the order of the fields.
http://teamcity.codebetter.com/viewLog.html?buildId=lastSuccessful&buildTypeId=bt66&tab=artifacts&guest=1
Cheers