Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Merge Sort in F# #4521

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Merge FSharp/src/Merge.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module Merge

let rec merge list1 list2 =
match list1, list2 with
| [], ys -> ys // If either list is empty, return the other
| xs, [] -> xs
| x::xs, y::ys when x <= y -> // Compare heads of both lists
x :: merge xs (y::ys) // Take smaller element (x) and recurse
| x::xs, y::ys ->
y :: merge (x::xs) ys // Otherwise take y and recurse
13 changes: 13 additions & 0 deletions Merge FSharp/test/MergeTests.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module MergeTests

[<Tests>]
let tests =
testList "Merge Tests" [
testCase "Merge two sorted lists" <| fun _ ->
let result = merge [1;3;5] [2;4;6]
Expect.equal result [1;2;3;4;5;6] "Should merge sorted lists"

testCase "Merge with empty list" <| fun _ ->
let result = merge [] [2;4;6]
Expect.equal result [2;4;6] "Should handle empty first list"
]
13 changes: 13 additions & 0 deletions Merge FSharp/test/mergeExample.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>f# 8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="src/Merge.fs" />
<Compile Include="test/MergeTests.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Expecto" Version="12.8.403.0" />
</ItemGroup>
</Project>
1 change: 1 addition & 0 deletions sample-programs
Submodule sample-programs added at f01513