Skip to content

Instantly share code, notes, and snippets.

@dasch
Last active November 21, 2018 14:42
Show Gist options
  • Save dasch/9b2a4a02b68a903a4e037b17f6a74daf to your computer and use it in GitHub Desktop.
Save dasch/9b2a4a02b68a903a4e037b17f6a74daf to your computer and use it in GitHub Desktop.
Monad syntax in Elm
module Bencode.Parse exposing (parseString, Value)
import Parser exposing (Parser)
import Dict exposing (Dict)
type Value
= BencString String
| BencInt Int
| BencList (List Value)
| BencDict (Dict String Value)
parseString : String -> Result String Value
parseString input =
Parser.run value input
value : Parser Value
value =
Parser.oneOf [ string, int, list, dict ]
string : Parser Value
string = do
length <- Parser.integer
Parser.symbol ":"
str <- Parser.bytes length
return (BencString str)
int : Parser Value
int = do
symbol "i"
integer <- Parser.int
symbol "e"
return (BencInt integer)
list : Parser Value
list = do
symbol "l"
elements <- Parser.zeroOrMore value
symbol "e"
return (BencList elements)
dict : Parser Value
dict = do
symbol "d"
elements <- Parser.zeroOrMore kvPair
symbol "e"
return (BencDict (Dict.fromList elements))
kvPair : Parser (String, Value)
kvPair = do
key <- string
val <- value
return (key, val)
import Spec exposing (..)
import Expect
suite : Suite
suite =
describe "Set" do
describe "singleton" do
it "builds a set with a single element" do
set <- Set.singleton "hello"
expectElements ["hello"] set
describe "fromList" do
it "builds a set of unique elements from the list" do
set <- Set.fromList ["hello", "world", "hello"]
expectElements ["hello", "world"] set
describe "intersect" do
it "returns the elements found in both sets" do
set1 <- Set.fromList ["hello", "world"]
set2 <- Set.fromList ["hello", "planet"]
expectElements ["hello"] (Set.intersect set1 set2)
expectElements : List a -> Set a -> Expectation
expectElements expected set =
Expect.equalList expected (Set.toList set)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment