1

As part of my question (F# Threading Changing State Through Unfold) I stumbled upon a solution using the Seq.fold function, but the syntax looked strange to me.

Essentially:

items
|> Seq.fold (fun (someState) theItem -> ....) someInitialState

I get what it's doing functionally, but I'm not entirely sure how it's doing it...

Is specifying SomeState separately in parentheses creating a curried function that someInitialState is then being partially applied to?

I don't think this is something specific to the fold function, and is likely just utilising a functional principle that I'm not seeing.

Community
  • 1
  • 1
Clint
  • 6,133
  • 2
  • 27
  • 48

1 Answers1

3

Parentheses do nothing. This is just how the folder looks like.

If you look at the type of fold:

Seq.fold : ('State -> 'T -> 'State) -> 'State -> seq<'T> -> 'State

The folder function is of type 'State -> 'T -> 'State. This means it takes a state and an element, and returns a new state. And indeed it's curried, but that's not really important here.

The way fold uses that function is by taking the initial state, applying the folder to that initial state and the first element, then applying the folder to the resulting state and the second element, and so on...

scrwtp
  • 13,437
  • 2
  • 26
  • 30
  • So presumably a fold of `fun item -> ...` with no additional state is an overload? OR is it just implicitly accepting unit? – Clint Jul 16 '15 at 15:58
  • I would say it's a fold used in a wrong way ;) There's no such overload in standard, perhaps it's something you have wrote in-house (in which case I suggest taking a good look at it). – scrwtp Jul 16 '15 at 16:03
  • It could be a partially applied folder, but to match the signature the first argument would be the accumulator rather than item. – scrwtp Jul 16 '15 at 16:06
  • I think I've actually had a brainfart and forgotten what fold **actually** is and as a result confused it with something else, forgetting that fold is taking state and reducing. – Clint Jul 16 '15 at 16:07
  • The basic answer to my question here is "the fold is doing a fold and you've been silly" haha. – Clint Jul 16 '15 at 16:17
  • 1
    @Clint - you might be thinking of [`Seq.reduce`](https://msdn.microsoft.com/en-us/library/ee353740.aspx) which is similar to `fold` except that it doesn't have a separate State parameter. – Joel Mueller Jul 17 '15 at 19:44
  • @Clint - Don't worry, it happens to us all! But if you don't think this question will be useful to anyone in future, you might as well delete it. – TheQuickBrownFox Jul 18 '15 at 10:48