Skip to content

Instantly share code, notes, and snippets.

@nskeip
Last active July 9, 2017 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nskeip/bb9db7a0aeb90fd1b9646d14bae38157 to your computer and use it in GitHub Desktop.
Save nskeip/bb9db7a0aeb90fd1b9646d14bae38157 to your computer and use it in GitHub Desktop.
Parsing forms suggestion for Dashdo project
{-# LANGUAGE OverloadedStrings, ExistentialQuantification, ExtendedDefaultRules, FlexibleContexts, Rank2Types, TemplateHaskell #-}
module Demo where
import Data.Monoid ((<>))
import Lens.Micro.Platform
data ExampleParams = ExampleParams
{ _foo :: Int
, _bar :: [Int]
} deriving (Show)
makeLenses ''ExampleParams
parseForm :: a -> [(Int, (a -> String -> a))] -> [(String, String)] -> a
parseForm x [] _ = x
parseForm x ((n,f):nfs) pars =
let fldName = "f"<> (show n)
newx = case lookup fldName pars of
Just lt -> f x lt
Nothing -> case filter ((== fldName <> "[]") . fst) pars of
[] -> x
listParams -> foldl f x (map snd listParams)
in parseForm newx nfs pars
fooUpdater :: ExampleParams -> String -> ExampleParams
fooUpdater ep s = set foo (read s :: Int) $ ep
barUpdater :: ExampleParams -> String -> ExampleParams
barUpdater ep s = over bar ((:) (read s :: Int)) $ ep
handlers = [(0, fooUpdater), (1, barUpdater)]
queryParams = [("f0", "100"), ("f1[]", "900"), ("f1[]", "1000"), ("f1[]", "2000")]
main = parseForm (ExampleParams 0 []) handlers queryParams
{-
> main
ExampleParams {_foo = 100, _bar = [2000,1000,900]}
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment