Implement a method that prints output without object-oriented support? - f#

Would I have to resort to F#'s object oriented design support to implement a method that returns void?
Specifically, what if I just wanted to print a message within a function?
Would I just have to create a member method within F# to accomplish this?
Example:
dealPlayer Hit {Face = Ace; Suit = Spades}
NOTE:
I am still learning F#. I'm apologize if this question appears ignorant.
type Suit = | Spades
| Clubs
| Diamonds
| Hearts
type Face = | Two | Three | Four | Five
| Six | Seven | Eight | Nine | Ten
| Jack | Queen | King | Ace
type Card = {Face:Face; Suit:Suit}
type Deal = | Hand of Card * Card
| Hit of Card
let dealPlayer dealType =
match dealType with
| Hand (card1, card2) -> printfn "%A" (card1, card2)
| Hit card -> printfn "%A" card
dealPlayer Hit {Face = Ace; Suit = Spades}

As #Functional_S answers, you can use printfn, but as a general observation, one of the main benefits of functional programming is to avoid side-effects.
Ultimately, all programs have side-effects, but the functional approach is to push the side-effects to the edge of whatever system you're building. (Incidentally, this is also true for most maintainable, successful object-oriented architectures; only you get less support from languages like C# or Java for doing that.)
So instead of letting dealPlayer have side-effects, make it a pure function:
let dealPlayer dealType =
match dealType with
| Hand (card1, card2) -> sprintf "%A" (card1, card2)
| Hit card -> sprintf "%A" card
This changes the type of the function to Deal -> string. (The name of the function may now be a bit misleading, though.)
At the edge of your system, you can still print the value if you want to, by piping the string to printfn:
> dealPlayer (Hit {Face = Ace; Suit = Spades}) |> printfn "%s";;
{Face = Ace;
Suit = Spades;}
val it : unit = ()
That's much more flexible because you postpone the decision to introduce side-effects until such a time that you can no longer postpone it.

You can use this, it print pretty well for small samples
let print x = printfn "%+A" x
Or if you need a return value
let toString x = sprintf "%+A" x

Related

is there a practical difference between this two getters, in F#?

I'm wondering about the two syntax for the getters:
type Direction =
| Undefined
| Buy
| Sell
member this.Symbol =
match this with
| Direction.Buy -> '↑'
| Direction.Sell -> '↓'
| Direction.Undefined -> '→'
member this.Symbol2 with get() =
match this with
| Direction.Buy -> '↑'
| Direction.Sell -> '↓'
| Direction.Undefined -> '→'
Is there any practical difference between the first one and the second one?
The IL looks identical, but from the usage standpoint? is one preferred for any reason?
They are identical, yes. In general, prefer the first one. The reason why the second one exists is if you have some special logic to do that isn't just grabbing a value. It's more flexible, but more syntax.

What is the | symbol for in f #?

I'm pretty new to functional programming and I've started looking at the documentation for match statements and in the example I came across here gitpages and cut and pasted to my question below:
let rec fib n =
match n with
| 0 -> 0
| 1 -> 1
| _ -> fib (n - 1) + fib (n - 2)
I understand that let is for static binding in this case for a recursive function called fib which takes a parameter n. It tries to match n with 3 cases. If it's 0, 1 or anything else.
What I don't understand is what the | symbol is called in this context or why it is used? Anything I search for pertaining to f-sharp pipe takes me to this |> which is the piping character in f sharp.
What is this | used for in this case? Is it required or optional? And when should be and shouldn't I be using |?
The | symbol is used for several things in F#, but in this case, it serves as a separator of cases of the match construct.
The match construct lets you pattern match on some input and handle different values in different ways - in your example, you have one case for 0, one for 1 and one for all other values.
Generally, the syntax of match looks like this:
match <input> with <case_1> | ... | <case_n>
Where each <case> has the following structure:
<case> = <pattern> -> <expression>
Here, the | symbol simply separates multiple cases of the pattern matching expression. Each case then has a pattern and an expression that is evaluated when the input matches the pattern.
To expand on Tomas's excellent answer, here are some more of the various uses of | in F#:
Match expressions
In match expressions, | separates the various patterns, as Tomas has pointed. While you can write the entire match expression on a single line, it's conventional to write each pattern on a separate line, lining up the | characters, so that they form a visual indicator of the scope of the match statement:
match n with
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| 3 -> "three"
| _ -> "something else"
Discriminated Unions
Discriminated Unions (or DUs, since that's a lot shorter to type) are very similar to match expressions in style: defining them means listing the possibilities, and | is used to separate the possibilities. As with match expressions, you can (if you want to) write DUs on a single line:
type Option<'T> = None | Some of 'T
but unless your DU has just two possibilities, it's usually better to write it on multiple lines:
type ContactInfo =
| Email of string
| PhoneNumber of areaCode : string * number : string
| Facebook of string
| Twitter of string
Here, too, the | ends up forming a vertical line that draws the eye to the possibilities of the DU, and makes it very clear where the DU definition ends.
Active patterns
Active patterns also use | to separate the possibilities, but they also are wrapped inside an opening-and-closing pair of | characters:
let (Even|Odd) n = if n % 2 = 0 then Even else Odd // <-- Wrong!
let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd // <-- Right!
Active patterns are usually written in the way I just showed, with the | coming immediately inside the parentheses, which is why some people talk about "banana clips" (because the (| and |) pairs look like bananas if you use your imagination). But in fact, it's not necessary to write the (| and |) characters together: it's perfectly valid to have spaces separating the parentheses from the | characters:
let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd // <-- Right!
let ( |Even|Odd| ) n = if n % 2 = 0 then Even else Odd // <-- ALSO right!
Unrelated things
The pipe operator |> and the Boolean-OR operator || are not at all the same thing as uses of the | operator. F# allows operators to be any combination of symbols, and they can have very different meanings from an operator that looks almost the same. For example, >= is a standard operator that means "greater than". And many F# programs will define a custom operator >>=. But although >>= is not defined in the F# core library, it has a standard meaning, and that standard meaning is NOT "a lot greater than". Rather, >>= is the standard way to write an operator for the bind function. I won't get into what bind does right now, as that's a concept that could take a whole answer all on its own to go through. But if you're curious about how bind works, you can read Scott Wlaschin's series on computation expressions, which explains it all very well.

Is there a name for this pattern "type 'a foldedSequence = Empty | Value of 'a * (unit->'a foldedSequence )"

I have been working with some f# parsers and some streaming software and I find myself using this pattern more and more. I find it to be a natural alternative to sequences and it has some natural advantages.
here are some example functions using the type.
type foldedSequence<'a> =
| Empty
| Value of ' a * (unit -> 'a foldedSequence)
let rec createFoldedSequence fn state =
match fn state with
| None -> Empty
| Some(value, nextState) ->
Value(value, (fun () -> unfold fn nextState))
let rec filter predicate =
function
| Empty -> Empty
| Value(value, nextValue) ->
let next() = filter predicate(nextValue())
if predicate value then Value(value, next)
else next()
let toSeq<'t> =
Seq.unfold<'t foldedSequence, 't>(function
| Empty -> None
| Value(value, nextValue) -> Some(value, nextValue()))
It has been very helpful I would like to know if it has a name so I can research some tips and tricks for it
To add to the existing answers, I think Haskellers might call a generalised version of this this a list monad transformer. The idea is that your type definition looks almost like ordinary F# list except that there is some additional aspect to it. You can imagine writing this as:
type ListTransformer<'T> =
| Empty
| Value of 'T * M<ListTransformer<'T>>
By supplying specific M, you can define a number of things:
M<'T> = 'T gives you the ordinary F# list type
M<'T> = unit -> 'T gives you your sequence that can be evaluated lazily
M<'T> = Lazy<'T> gives you LazyList (which caches already evaluated elements)
M<'T> = Async<'T> gives you asynchronous sequences
It is also worth noting that in this definition LazyTransformer<'T> is not itself a delayed/lazy/async value. This can cause problems in some cases - e.g. when you need to perform some async operation to decide whether the stream is empty - and so a better definition is:
type ListTransformer<'T> = M<ListTransformerInner<'T>>
and ListTransformerInner<'T> =
| Empty
| Value of 'T * ListTransformer<'T>
This sounds like LazyList which used to be in the "powerpack" and I think now lives here:
http://fsprojects.github.io/FSharpx.Collections/reference/fsharpx-collections-lazylist-1.html
https://github.com/fsprojects/FSharpx.Collections/blob/master/src/FSharpx.Collections/LazyList.fs
Your type is close to how an iteratee would be defined, and since you already mention streaming, this might be the concept you're looking for.
Iteratee IO is an approach to lazy IO outlined by Oleg Kiselyov. Apart from Haskell, implementations exist for major functional languages, including F# (as part of FSharpx.Extras).
This is how FSharpx defines an Iteratee:
type Iteratee<'Chunk,'T> =
| Done of 'T * Stream<'Chunk>
| Error of exn
| Continue of (Stream<'Chunk> -> Iteratee<'Chunk,'T>)
See also this blog post: Iteratee in F# - part 1. Note that there doesn't seem to be a part 2.

Check several option types and then convert to type

I am a new programmer in general, and as well to F#. I've ran into this particular problem several times, and have yet to solve it efficiently in my opinion. Here is the problem:
I have these example types:
type Retail1 = | Fashion | Auto | Sports
type Wholesale1 = | Fashion | Auto | Sports
type Events1 = | Wedding | Birthday
type Product =
| Retail of Retail1 | Wholesale of Wholesale1 | Events of Events1
| NoProduct
I want to convert the possibility of the first three types to the Product type via a function:
let convertToProduct (retail: Retail1 option)
(wholesale: Wholesale1 option) (events: Events1 option) =
// convert to Product here
if retail.IsSome then Retail retail
elif wholesale.IsSome then Wholsale wholseale
elif events.IsSome then Events events
else NoProduct
The way that I have handled it in the pass is just to chain a long if elif statement together to check for each condition and return the final type of Product, but this does not feel correct, or at the very least idiomatic to F#. What would be the recommended approach to this problem?
How about something like this:
let convertToProduct (retail: Retail1 option) (wholesale: Wholesale1 option) (events: Events1 option) =
match (retail, wholesale, events) with
|Some rt, None, None -> Retail rt
|None, Some wh, None -> Wholesale wh
|None, None, Some ev -> Events ev
|_ -> NoProduct
This exploits the fact that if you convert all the arguments into a tuple, you can do pretty concise pattern matching on the result.
Pattern matching is actually extremely powerful, you can find more details about the types of pattern matching you can perform in the MSDN documentation.

Comparing F# discriminated union instances via pattern matching

Firstly, apologies for the poor title - I don't understand enough F# to describe the problem better.
Consider this simple DU:
type Money =
| USD of decimal
| GBP of decimal
| EUR of decimal
static member (+) (first: Money, second: Money) =
match first, second with
| USD(x), USD(y) -> USD(x + y)
| GBP(x), GBP(y) -> GBP(x + y)
| EUR(x), EUR(y) -> EUR(x + y)
| _ -> failwith "Different currencies"
I'm representing money in different currencies, and overloading the (+) operator so that I can safely do Money + Money. However, if I have many currencies then the match statement will become tedious to write. Is there any way of expressing something like:
match first, second with
| _(x), _(y) -> _(x + y)
Or is there a different way to achieve the same result? I've considered and discarded units of measure due to the limitations described here.
Does this work for you?
type Kind = | USD | GBP | EUR
type Money =
| Money of Kind * decimal
static member (+) (first: Money, second: Money) =
match first, second with
| Money(k1,x), Money(k2,y) when k1=k2 -> Money(k1, x + y)
| _ -> failwith "Different currencies"

Resources