본문 바로가기
Ocaml

[99 Problems in OCaml] 14번, 15번 문제

by seungh2 2021. 9. 23.

99 Problems in OCaml

https://ocaml.org/learn/tutorials/99problems.html

 

99 problems – OCaml

Your Help is Needed Many of the solutions below have been written by Victor Nicollet. Please contribute more solutions or improve the existing ones. 99 Problems (solved) in OCaml This section is inspired by Ninety-Nine Lisp Problems which in turn was based

ocaml.org

 

14번 문제

  • duplicate
    • duplicate list
    • list의 각 원소를 1개씩 더 추가한다.

 

내가 구현한 코드

안에 로컬함수를 만들어서 ans에 값을 누적하였다.

 

정답 코드

완전 간단해서 놀랐다.

근데 이해가 안되서 직접 해보고나서 이해를 했다.

만약 인자로 [a; b; c]가 들어오면

a :: a :: duplicate_sol [b; c]

-> a :: a :: (b :: b :: duplicate_sol [c])

-> a :: a :: (b :: b :: (c :: c :: duplicate_sol []))

-> a :: a :: (b :: b :: (c :: c :: []))

-> [a; a; b; b; c; c]

 

test 결과

15번 문제

  • replicate
    • replicate list number
    • list의 각 원소를 number개의 같은 원소를 갖는 리스트를 반환한다.

 

내가 구현한 코드

list의 각 원소마다 number개의 원소를 넣어야하기 때문에 이를 수행하는 repeat 함수를 작성하고 answer함수에서 list의 각 원소에 대해 repeat함수를 수행한다.

 

test 결과

 

 

728x90

댓글