Thursday, 15 May 2014

Is writing helper functions for state passing style idiomatic in Haskell? -



Is writing helper functions for state passing style idiomatic in Haskell? -

i'm working on code card game:

splitcards_ (x:xs) (a,b,c) | isgold x = splitcards xs (a:x,b,c) | isaction x = splitcards xs (a,b:x,c) | isvp x = splitcards xs (a,b,c:x) splitcards_ [] (a,b,c) = (a,b,c) splitcards xs = splitcards_ xs ([],[],[])

essentially, taking list of cards, , splitting 3 different lists depending on type of card. splitcards_ represents state updates recursively updating it's parameters, splitcards (the actual function) used start computation 3 lists of specific types of cards empty.

i believe called state-passing style, , i'm pretty sure that's idiomatic, i'm more concerned fact have define helper function splitcards_ in order work way want. creating helper functions idiomatic haskell? there cleaner way write this? there naming conventions preferable putting underscore on end of name of helper function?

yes, idiomatic style. it's classic way create function tail recursive. (although that's less of import , more nuanced in haskell).

moreover, making helper functions , key part of many mutual patterns. if sense more natural factored out, go it! unless it's taken extreme, helps readability.

the main suggestion have putting helper function where clause. way, visible in scope of main function makes clear it's helper. name give helper function less important; splitcards_ fine, splitcards' (pronounced "splitcards prime") , go (a generic name helper functions) more common. rewrite code this:

splitcards xs = go xs ([],[],[]) go (x:xs) (a, b, c) | isgold x = go xs (a:x,b,c) | isaction x = go xs (a,b:x,c) | isvp x = go xs (a,b,c:x) go [] (a, b, c) = (a, b, c)

note these cosmetic changes—what doing fundamentally sound.

the 2 naming options (go vs splitcards') matter of preference.

i go because, 1 time you're used convention, signals helper function. in sense, go more syntax function of own; it's meaning purely subordinate splitcards function.

others not go because little cryptic , arbitrary. might create recursive construction of code less clear because you're recursing on go , not function itself.

go whatever think looks best.

haskell idiomatic

No comments:

Post a Comment