```fsharp
match students with
|_ when students.Length = 1 -> students.[0].Name
|_ when students.[0].getStudentAmount = students.[1].getStudentAmount -> "All"
|_ -> students.[0].Name
```
student_1=Student(name="richard",fives=25,tens=5,twenties=5)student_2=Student(name="helen",fives=55,tens=5,twenties=5)print(most_amount([student_1,student_2]))# helen
packageeducationimport"testing"typebaseTestCasestruct{descriptionstring}varbob=Student{"Bob",4,0,0}varmary=Student{"Mary",0,2,0}varjohn=Student{"John",0,0,1}vargoat=Student{"Goat",0,0,0}varrichie=Student{"Richie",10,20,100}funcTestTrip_Richest(t*testing.T){testCases:=[]struct{baseTestCaseinputTripexpectedstring}{{baseTestCase{"no students"},Trip{},"none",},{baseTestCase{"one student"},Trip{[]Student{mary}},mary.Name,},{baseTestCase{"many students with same amount of funds"},Trip{[]Student{mary,bob,john}},"all",},{baseTestCase{"many students with one having more"},Trip{[]Student{mary,bob,goat,richie}},richie.Name,},}for_,test:=rangetestCases{ifresult:=test.input.Richest();result!=test.expected{t.Fatalf("FAIL: %s - %+v.Funds(): '%s' - expected: '%s'",test.baseTestCase.description,test.input,result,test.expected)}t.Logf("PASS: %s",test.baseTestCase.description)}}funcTestStudent_Funds(t*testing.T){testCases:=[]struct{baseTestCaseinputStudentexpectedint}{{baseTestCase{"no moniez"},goat,0,},{baseTestCase{"only fives"},bob,20,},{baseTestCase{"only tens"},mary,20,},{baseTestCase{"only twenties"},john,20,},{baseTestCase{"all the moniez"},richie,2250,},}for_,test:=rangetestCases{ifresult:=test.input.Funds();result!=test.expected{t.Fatalf("FAIL: %s - %+v.Funds(): %d - expected: %d",test.baseTestCase.description,test.input,result,test.expected)}t.Logf("PASS: %s",test.baseTestCase.description)}}
data classStudent(valname:String,valfives:Int,valtens:Int,valtwenties:Int)privatevalStudent.total:Intget()=fives*5+tens*10+twenties*20sealedclassStudentAccumulator{abstractvalmoney:Int}objectEmpty:StudentAccumulator(){overridevalmoney=0}data classErrorFound(valmessage:String):StudentAccumulator(){overridevalmoney=0}data classMaxFound(valname:String,overridevalmoney:Int):StudentAccumulator()data classTieFound(overridevalmoney:Int):StudentAccumulator()fungenerateStudentFolder(compareFn:(StudentAccumulator,Student)->Int)={acc:StudentAccumulator,student:Student->when(acc){isErrorFound->accisEmpty->MaxFound(student.name,student.total)isMaxFound->acc.consider(student,compareFn)isTieFound->acc.consider(student,compareFn)}}funMaxFound.consider(student:Student,compareFn:(StudentAccumulator,Student)->Int)=when(compareFn(this,student)){-1->MaxFound(student.name,student.total)0->TieFound(student.total)else->this}funTieFound.consider(student:Student,compareFn:(StudentAccumulator,Student)->Int)=when(compareFn(this,student)){-1->MaxFound(student.name,student.total)0->ErrorFound("More than one maximum")else->this}funIterable<Student>.findMax()=fold(EmptyasStudentAccumulator,generateStudentFolder{a,b->a.money.compareTo(b.total)})funIterable<Student>.findMaxName():String{returnwhen(valresult=findMax()){isErrorFound->throwError(result.message)isEmpty->throwError("No max found")isMaxFound->result.nameisTieFound->"all"}}funmain(){valstudentsA=listOf(Student("a",1,1,1))println(studentsA.findMaxName())valstudentsB=listOf(Student("a",1,1,1),Student("b",1,1,1))println(studentsB.findMaxName())valstudentsC=listOf(Student("a",1,1,1),Student("c",2,1,1),Student("b",1,1,1))println(studentsC.findMaxName())}
It's typesafe, and we could change the comparator out if we wanted to. A little kludgey in the fold section (I should probably involve Option to avoid people accidentally calling money on the Empty and Error types. 🤷♀️
While I love the sealed class idea in Kotlin, type erasure and lack of true pattern matching really hampers the readability. If I was able to rely on StudentAccumulator auto-casting to its internal types, then I could remove a when statement that just dispatches out to the same overloaded call with the proper type.
Ok, I fixed it. It's not too much uglier with proper Option protection...
importarrow.core.Optionimportarrow.core.getOrElsedata classStudent(valname:String,valfives:Int,valtens:Int,valtwenties:Int)privatevalStudent.total:Intget()=fives*5+tens*10+twenties*20sealedclassStudentAccumulator{abstractvalmoney:Option<Int>}objectEmpty:StudentAccumulator(){overridevalmoney=Option.empty<Int>()}data classErrorFound(valmessage:String):StudentAccumulator(){overridevalmoney=Option.empty<Int>()}data classMaxFound(valname:String,overridevalmoney:Option<Int>):StudentAccumulator(){constructor(student:Student):this(student.name,Option.just(student.total))}data classTieFound(overridevalmoney:Option<Int>):StudentAccumulator(){constructor(student:Student):this(Option.just(student.total))}fungenerateStudentFolder(compareFn:(StudentAccumulator,Student)->Option<Int>)={acc:StudentAccumulator,student:Student->when(acc){isErrorFound->accisEmpty->MaxFound(student)isMaxFound->acc.consider(student,compareFn)isTieFound->acc.consider(student,compareFn)}}funMaxFound.consider(student:Student,compareFn:(StudentAccumulator,Student)->Option<Int>)=compareFn(this,student).map{result->when(result){-1->MaxFound(student)0->TieFound(student)else->this}}.getOrElse{ErrorFound("Bad comparison.")}funTieFound.consider(student:Student,compareFn:(StudentAccumulator,Student)->Option<Int>)=compareFn(this,student).map{result->when(result){-1->MaxFound(student)0->ErrorFound("More than one maximum")else->this}}.getOrElse{ErrorFound("Bad comparison.")}funIterable<Student>.findMax()=fold(EmptyasStudentAccumulator,generateStudentFolder{a,b->a.money.map{it.compareTo(b.total)}})funIterable<Student>.findMaxName():String{returnwhen(valresult=findMax()){isErrorFound->throwError(result.message)isEmpty->throwError("No max found")isMaxFound->result.nameisTieFound->"all"}}
Hello! I'm Seniru - a person who is trying to understand what the world is. I like pizza and coding and I find myself as a patient, self-confident and a systematic person with a strong desire
importrandomasrandclassStudent:def__init__(self,name,fives,tens,twenties):self.name=nameself.fives=fivesself.tens=tensself.twenties=twentiesdefgetMoney(self):returnself.fives*5+self.tens*10+self.twentiesdef__str__(self):returnself.name+" "+str(self.getMoney())#Creating a list of students
students=sorted([Student('Student'+str(s),rand.randint(0,10),rand.randint(0,10),rand.randint(0,10))forsinrange(20)],key=lambdas:s.getMoney(),reverse=True)forsinstudents:print(s)print('Student with highest amount:',end=' ')iflen(students)==1:print(students[1])elifstudents[0]==students[::-1]:print('All')else:print(students[0])
Using total_ordering decorator from func_tools, which only requires two implementations of the comparison methods.
fromfunctoolsimporttotal_ordering@total_orderingclassStudent:def__init__(self,name,fives,tens,twenties):self.name=nameself.fives=fivesself.tens=tensself.twenties=twenties# Added new property
self.money=self.fives*5+self.tens*10+self.twenties*20def__eq__(self,other):returnself.money==other.moneydef__lt__(self,other):returnself.money<other.moneyst1=Student('Héctor',1,7,3)st2=Student('Albert',5,4,3)st3=Student('Jordi',1,4,3)students=[st1,st2,st3]print(max(students).name)
We're a place where coders share, stay up-to-date and grow their careers.
My first attempt at F#
I couldn't get the syntax highlighting for F# so if anyone can point me in the right direction that would be much appreciated.
```fsharp match students with |_ when students.Length = 1 -> students.[0].Name |_ when students.[0].getStudentAmount = students.[1].getStudentAmount -> "All" |_ -> students.[0].Name ```renders as
(HEY, dev.to maintainers, this is one of those "won't fix bugs!" 😠 Why can't I nest backticks as in the github flavored markdown spec?)
Thank you
there is nothing more beautiful than Python
Usage:
Hi, check this decorator :
docs.python.org/3/library/functool...
Will make you avoid writing some functions.
Thank you Héctor i didn't know about this.
I've tried to apply it but it looks is a little shady for me, i didn't quite understand what is does and how it "magically" does the comparison
I put myself in here as a test case as a joke because I didn't get an allowance as a kid 😂
education.go
education_test.go
Thank you Michael. I have been following your F# posts in this series and found them very helpful.
I thought about using a record type but thought it would be easier to use a class property for the match function.
If you get chance please could you show how you would approach the full solution.
Many thanks.
Here is the Python code snippets:
Ridiculously over-engineered Kotlin version:
It's typesafe, and we could change the comparator out if we wanted to. A little kludgey in the fold section (I should probably involve Option to avoid people accidentally calling money on the
EmptyandErrortypes. 🤷♀️While I love the
sealed classidea in Kotlin, type erasure and lack of true pattern matching really hampers the readability. If I was able to rely onStudentAccumulatorauto-casting to its internal types, then I could remove a when statement that just dispatches out to the same overloaded call with the proper type.Ok, I fixed it. It's not too much uglier with proper Option protection...
Javascript:
Usage:
My try with python
In Scala -
Wow. Very good. I was nowhere near getting this. I need to spend some time working through your solution.
Thank you - it is very instructional. I really like how you show your tests as well. I haven't quite got my head around setting up tests in F# yet.
My Python attempt :
Using total_ordering decorator from func_tools, which only requires two implementations of the comparison methods.